[英]Get weird output with char array C++
我正在嘗試從文件中讀取數據並將其存儲到字符數組中。 大部分是成功的,但我得到了一個奇怪的輸出。 代碼函數如下所示:
char* read_answers() {
string fileName, data;
char* answer = new char [50];
ifstream inFile;
while(!inFile.is_open()){
//cout<<endl<<"Please enter the name of the answers file: ";
//cin>>fileName;
inFile.open("answers.txt");
if (!inFile.is_open()){
cout << "Error opening file" << endl;
}
}
for (int i = 0; i < 50; i++) {
if (inFile.eof())
continue;
inFile.get(answer[i]);
cout << i << answer[i] << endl;
}
inFile.close();
cout << answer[0];
cout << answer[1];
cout << answer[2];
return answer;
}
該文件如下所示:
C
A
C
A
B
D
D
輸出如下所示:
0C
1
2A
3
4C
5
6A
7
8B
9
10D
11
12D
13
14═
C
A
對我來說,它看起來像是將空數據存儲到數組中。 反正有沒有跳過讀取空白數據?
這里的問題是 END OF LINE 字符( \\n
)。
嘗試用這個改變你for
:
int i=0;
while (i < 49 && inFile.get(tmp)){
char tmp;
inFile.get(tmp);
if (tmp != '\n'){
answer[i] = tmp;
cout << i << answer[i] << endl;
i++;
}
}
answer[i] = '\0';
最后一行保證字符串在內存中得到很好的表示
您沒有考慮到inFile.get()
還會讀取並返回換行符,然后您的循環會輸出這些字符。 這就是為什么您的輸出中有空格的原因。
您的代碼中還有其他錯誤,例如在inFile.open()
失敗時陷入無限循環,以及濫用inFile.eof()
。
試試這個:
char* read_answers() {
//string fileName;
//cout << "Please enter the name of the answers file: ";
//cin >> fileName;
ifstream inFile("answers.txt");
if (!inFile.is_open()) {
cerr << "Error opening file" << endl;
return NULL;
}
char* answer = new char [51];
char ch;
int i = 0;
while ((i < 50) && inFile.get(ch)) {
if ((ch != ' ') && (ch != '\r') && (ch != '\n')) {
cout << i << ch << endl;
answer[i] = ch;
++i;
}
}
answer[i] = '\0';
inFile.close();
cout << answer[0];
cout << answer[1];
cout << answer[2];
return answer;
}
或者:
char* read_answers() {
//string fileName;
//cout << "Please enter the name of the answers file: ";
//cin >> fileName;
ifstream inFile("answers.txt");
if (!inFile.is_open()) {
cerr << "Error opening file" << endl;
return NULL;
}
char* answer = new char [51];
int i = 0;
while ((i < 50) && (inFile >> answer[i])) {
cout << i << answer[i] << endl;
++i;
inFile.ignore(numeric_limits<streamsize>::max(), '\n');
}
answer[i] = '\0';
inFile.close();
cout << answer[0];
cout << answer[1];
cout << answer[2];
return answer;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.