2016-07-05 3 views
-1

firstFileStream[50]이라는 문자 배열이 있는데, 이는 fstream을 사용하여 infile에서 기록됩니다.어떻게 char 배열을 C++의 문자열로 변환 할 수 있습니까?

이 문자 배열을 firstFileAsString이라는 문자열로 변환하고 싶습니다. string firstFileAsString = firstFileStream;을 쓰면 배열 내의 첫 번째 단어 만 쓰고 첫 번째 공백이나 빈 문자에서 멈 춥니 다. 내가 firstFileAsString(firstFileStream)이라고 쓰면 나는 같은 출력을 얻는다.

어떻게 전체 문자 배열을 그 안에있는 모든 단어를 문자열로 쓰나요? zdan가 지적했듯이, 난 단지 파일의 첫 번째 단어를 읽고 있었다, 그래서 대신 내가 지정하는 istreambuf_iterator<char>을 사용했습니다,

string firstInputFile = "inputText1.txt"; 
char firstFileStream[50]; 

ifstream openFileStream; 
openFileStream.open(firstInputFile); 

if (strlen(firstFileStream) == 0) { // If the array is empty 
    cout << "First File Stream: " << endl; 
    while (openFileStream.good()) { // While we haven't reached the end of the file 
     openFileStream >> firstFileStream; 
    } 
    string firstFileAsString = firstFileStream; 

} 
+0

어떻게 당신은 얼마나 많은 문자를 복사하는 지 알고 있나요? – juanchopanza

+0

입력 파일의 길이가 공백을 포함하여 해당 문자 수를 포함합니다. – fauliath

+0

@ Magis 50자를 복사해야하는지 또는 일부 비밀 번호입니까? – juanchopanza

답변

0

내 문제 : 다음

는에서 읽고 쓰는 코드입니다 문자 배열보다 먼저 문자열에 직접 내용을 전달합니다. 이것은 문자 배열로 나눌 수 있습니다.

0
openFileStream >> firstFileStream; 

은 파일에서 한 단어 만 읽습니다.

(적어도 완충 능력까지) 전체 파일을 읽기의 간단한 예는 다음과 같습니다

openFileStream.read(firstFileStream, sizeof(firstFileStream) - 1); 
// sizeof(firstFileStream) - 1 so we have space for the string terminator 
int bytesread; 
if (openFileStream.eof()) // read whole file 
{ 
    bytesread = openFileStream.gcount(); // read whatever gcount returns 
} 
else if (openFileStream) // no error. stopped reading before buffer overflow or end of file 
{ 
    bytesread = sizeof(firstFileStream) - 1; //read full buffer 
}  
else // file read error 
{ 
    // handle file error here. Maybe gcount, maybe return. 
} 
firstFileStream[bytesread] = '\0'; // null terminate string 
관련 문제