从带有空间的.txt中读取完整的文本,为单个变量C

Reading a full line of text from .txt with white space into a single variable C++

本文关键字:文本 单个 变量 读取 空间 txt      更新时间:2023-10-16

我从文件中读取了一些麻烦。

我的文件包含多行,所有行都需要将所有行保存到不同类型的变量中。我能够获得布尔和INT的正确转移,但是我的字符串遇到了麻烦,特别是包含空白的字符串。

我的文件包含:

1
0  
1  
0  
0  
0
1
0
0
0
Chester Von Tester
1
1

我能够使每条线正确阅读到单个变量中,但是当它到达切斯特·von Tester时,它会吓坏了,要么只输入第一个单词,要么根本没有根据我使用的方法来输入。

这是代码的花序不正确的(整个代码为几百行),不要认为有必要发布):

loadGame >> newGame;
cout << typeid(newGame).name() << " " << newGame << endl;
loadGame >> bossOne;
cout << typeid(bossOne).name() << " " << bossOne << endl;
loadGame >> bossTwo;
cout << typeid(bossTwo).name() << " " << bossTwo << endl;
loadGame >> bossThree;
cout << typeid(bossThree).name() << " " << bossThree << endl;
loadGame >> bossFour;
cout << typeid(bossFour).name() << " " << bossFour << endl;
loadGame >> bossFive;
cout << typeid(bossFive).name() << " " << bossFive << endl;
loadGame >> bossDeathCount;
cout << typeid(bossDeathCount).name() << " " << bossDeathCount << endl;
//Position Coordinates
loadGame >> coord_x;
cout << typeid(coord_x).name() << " " << coord_x << endl;
loadGame >> coord_y;
cout << typeid(coord_y).name() << " " << coord_y << endl;
loadGame >> inCombat;
cout << typeid(inCombat).name() << " " << inCombat << endl;
//Character traits
getline(loadGame,characterName);
cout << typeid(characterName).name() << " " << characterName << endl;
loadGame >> characterGender;
cout << typeid(characterGender).name() << " " << characterGender << endl;
loadGame >> characterClass;
cout << typeid(characterClass).name() << " " << characterClass << endl;

这是代码运行时发生的事情:

b 1
b 0
b 1
b 0
b 0
b 0
i 1
i 0
i 0
b 0
Ss 
i 0
i 1

它可以使所有类型ID正确,这是一个开始。它弄乱的地方是说" ss"的名称,然后在应该说" SS Chester von tester"的时候空白,然后是" I 1"不是" I 0"。

将整个行"切斯特von Tester"进入该字符串变量是什么?

随着发布代码,很难理解您要做什么。您可以使用std::getline函数,该函数将通过函数调用读取一行。