C++ 输出数据重叠?
C++ outputted data overlaps?
我正在编写一个读取文本文件并输出数据的程序。例如,数据的一个“条目”如下所示:
Alexander, Maurice
DB
1
0
0
0
0
我已经编写了一些代码来读取第一个条目并将其输出。
struct playerType{
string name;
string position;
int touchdowns;
int catches;
int yardsPass;
int yardsRsh;
int yardsRcv;
};
int main(){
ifstream inData;
inData.open("data.txt");
playerType players[10];
getline(inData >> ws, players[0].name, '\n');
inData.clear();
cout << players[0].name << endl;
inData >> players[0].position;
cout << players[0].position << endl;
inData >> players[0].touchdowns;
cout << players[0].touchdowns << endl;
inData >> players[0].catches;
cout << players[0].catches << endl;
inData >> players[0].yardsPass;
cout << players[0].yardsPass << endl;
inData >> players[0].yardsRsh;
cout << players[0].yardsRsh << endl;
inData >> players[0].yardsRcv;
cout << players[0].yardsRcv << endl;
cout << endl << "After:" << endl;
cout << players[0].name << players[0].position << players[0].touchdowns
<< players[0].catches << players[0].yardsPass << players[0].yardsRsh
<< players[0].yardsRcv << endl;
}
我不确定为什么,但是当我在不同的行上输出结构的每个部分时,会输出正确的值。但是,当我在一行中输出所有内容时,name
会被后续变量重叠:
我确定我只是在某个地方犯了初学者的错误,但我似乎无法弄清楚为什么输出是这样的。我的印象是变量会一个接一个地输出,而不是相互重叠。
您必须替换所有回车-return + 换行符组合(在 Windows 上用作换行符但不被(某些发行版) Linux) 使用简单的换行符。
这是 some code 的做法:
#include <string>
#include <regex>
name = std::regex_replace(name, std::regex("\r\n"), "\n");
我正在编写一个读取文本文件并输出数据的程序。例如,数据的一个“条目”如下所示:
Alexander, Maurice
DB
1
0
0
0
0
我已经编写了一些代码来读取第一个条目并将其输出。
struct playerType{
string name;
string position;
int touchdowns;
int catches;
int yardsPass;
int yardsRsh;
int yardsRcv;
};
int main(){
ifstream inData;
inData.open("data.txt");
playerType players[10];
getline(inData >> ws, players[0].name, '\n');
inData.clear();
cout << players[0].name << endl;
inData >> players[0].position;
cout << players[0].position << endl;
inData >> players[0].touchdowns;
cout << players[0].touchdowns << endl;
inData >> players[0].catches;
cout << players[0].catches << endl;
inData >> players[0].yardsPass;
cout << players[0].yardsPass << endl;
inData >> players[0].yardsRsh;
cout << players[0].yardsRsh << endl;
inData >> players[0].yardsRcv;
cout << players[0].yardsRcv << endl;
cout << endl << "After:" << endl;
cout << players[0].name << players[0].position << players[0].touchdowns
<< players[0].catches << players[0].yardsPass << players[0].yardsRsh
<< players[0].yardsRcv << endl;
}
我不确定为什么,但是当我在不同的行上输出结构的每个部分时,会输出正确的值。但是,当我在一行中输出所有内容时,name
会被后续变量重叠:
我确定我只是在某个地方犯了初学者的错误,但我似乎无法弄清楚为什么输出是这样的。我的印象是变量会一个接一个地输出,而不是相互重叠。
您必须替换所有回车-return + 换行符组合(在 Windows 上用作换行符但不被(某些发行版) Linux) 使用简单的换行符。 这是 some code 的做法:
#include <string>
#include <regex>
name = std::regex_replace(name, std::regex("\r\n"), "\n");