C++ C++;输出数据重叠?
我正在写一个程序,读取一个文本文件并输出数据。例如,以下是数据的一个“条目”的外观:C++ C++;输出数据重叠?,c++,file-io,output,C++,File Io,Output,我正在写一个程序,读取一个文本文件并输出数据。例如,以下是数据的一个“条目”的外观: 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(){
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;
}
struct playerType{
字符串名;
串位置;
int触地得分;
int渔获物;
国际码通;
国际码;
国际码;
};
int main(){
Iftream inData;
open(“data.txt”);
playerType播放器[10];
getline(inData>>ws,players[0]。名称,'\n');
inData.clear();
cout玩家[0]。位置;
cout玩家[0]。触地得分;
cout玩家[0]。捕获;
cout玩家[0]。码传球;
cout players[0].yardsRsh;
cout players[0].yardsRcv;
cout您必须用简单的新行替换所有回车+新行字符组合(在Windows上用作新行,但Linux的某些发行版不理解)。
下面是做这件事的建议:
#include <string>
#include <regex>
name = std::regex_replace(name, std::regex("\r\n"), "\n");
#包括
#包括
name=std::regex\u replace(名称,std::regex(“\r\n”),“\n”);
看起来有一个CR字符(\r
)在名称的末尾。正如@1201programalam所说,必须有一个\r
字符。你能运行hextump-C data.txt
并给我们该命令的输出吗?@nikitademov这是该命令的输出:我以前听说过\r
字符,但以前从未使用过它。是什么导致了\r代码>要保存到变量中的字符?如何防止这种情况发生?@SamuelL。请参阅0d
(第二行,第三字节)?这是一个连珠炮式返回(\r
)字符。它将光标的位置设置为行的开头,但与\n
结合使用时,Windows也用于新行(Win:\r\n
,UNIX:\n
)。您的操作系统似乎无法检测到这种字符组合,因此将\r
解释为它的实际含义。这就是为什么我在Mac上可以看到它,但您在操作系统上却看不到。TL;DR:责怪Microsoft和您的操作系统太“愚蠢”。注意:您也必须为位置执行此操作。我明白了,让我在代码中尝试一下。我可以问一下为什么不需要为整数变量执行此操作吗?@SamuelL。因为\r
是字符串的一部分,就像字母一样。您的字符串不是“Alexander,Maurice”
,而是“Alexander,Maurice\r”
。整数只是一个数字——它不包含字母。这就把它清除了很多。谢谢!