2013-04-01 3 views
0

내가 입력 텍스트 파일에 문자열을 결합하는 것을 시도하고있다. 내 코드는 다음과 같습니다결합 문자열

`#include <iostream> 
#include <sstream> 
#include <fstream> 
#include <string> 

using namespace std; 

int main(){ 
int year; 
string line; 
string fileName; 

for (int i=1880; i<2012; i++){ 
    stringstream ss; 
    ss << year; 


fileName = string("yob") + string(year) + string(".txt"); 

ifstream ifile(fileName.c_str()); 
getline(ifile,line); 
cout << line << endl; 
ifile.close(); 
} 

}` 

텍스트 파일 < "yob1880.txt"처럼 - 그 첫 번째 텍스트 파일의 그것은 "yob2011.txt"모든 길을 간다. 하나씩 텍스트 파일을 입력하고 싶지만이 세 가지 문자열 유형을 결합하면 작동하지 않습니다. int에서 const char * 로의 잘못된 변환 오류가 발생합니다.

문제에 대한 의견이 있으십니까? 감사!

+0

변수'year'에는 아무 것도 지정하지 않았습니다. 그것은 주된 문제는 아니지만 그것은 문제 중 하나입니다. for 루프에'year = i;'를 설정 했는가? – maditya

+0

또한 어느 행이 오류입니까? – maditya

답변

0

당신은 그것은 이제 stringstream에서 받아야합니다. 거의 다 왔으니 대신 다음과 같이해야합니다.

#include <iostream> 
#include <sstream> 
#include <fstream> 
#include <string> 

using namespace std; 

int main(){ 
int year; 
string line; 
string fileName; 

for (int i=1880; i<2012; i++){ 
    year = i; //I'm assuming this is what you meant to use "year" for 
    stringstream ss; 
    ss << year; //add int to stringstream 

string yearString = ss.str(); //get string from stringstream 

fileName = string("yob") + yearString + string(".txt"); 

ifstream ifile(fileName.c_str()); 
getline(ifile,line); 
cout << line << endl; 
ifile.close(); 
} 

} 
+0

고마워요! 그건 의미가있다. – user22