dodawania stringow

0

Witam
mam napisac funkcje ktora prosi o podanie jakiegos tekstu ma sprawdzac czy na koncu jest rozszerzenie ".txt" jesli tak to ma wypisac jesli jest inne to ma zamienic na .txt, jesli nie ma nic to ma dodac .txt i w tym miejscu nie wiem jak to zrobic wyswietla blad out_of_range

// 531-XLVI.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

string dopisz();


int _tmain(int argc, _TCHAR* argv[])
{

	cout<<dopisz();
	getchar();
	return 0;
}

string dopisz()
{
	string nazwa;
	cout<<"Podaj nazwe: ";
	getline(cin,nazwa);

	string roz;

	if(nazwa.find_last_of("."))
	{
		roz=nazwa.substr(nazwa.find_last_of("."),4);

		if(roz==".txt")
			return nazwa;
		else
		{
			nazwa.replace(nazwa.find_last_of("."),999,".txt");
			return nazwa;
		}
	}
	/*else
	{
		nazwa+=".txt";
		return nazwa;
	} */


}
0

Czy tak nie jest prościej?:

string wymusRozszerzenie(const string& file) {
     int pos;
     string result(file);

     pos = result.find_last_of(".");
     if (pos>0) {
          result.resize(pos);
     }
     result += ".txt";
     return result;
}
0
MarekR22 napisał(a)

Czy tak nie jest prościej?:

string wymusRozszerzenie(const string& file) {
     int pos;
     string result(file);

     pos = result.find_last_of(".");
     if (pos>0) {
          result.resize(pos);
     }
     result += ".txt";
     return result;
}

wlasciwie moglo by byc tylko ta funkcja nawet jak jest rozszerzenie .txt to je na nowo wstawia a chodzilo o to ze jak juz jest .txt to zeby nic nie robila

1 użytkowników online, w tym zalogowanych: 0, gości: 1