逐行从文本文件中读取 |C++

reading from a textfile line by line | C++

本文关键字:读取 C++ 文件 文本 逐行      更新时间:2023-10-16

我现在在互联网上搜索了一段时间,但找不到适合我的解决方案。 或者我只是哑巴。 我在一个.txt文件中有 12 行,我想一行地阅读这些。从 1,2...12 开始。 我的.txt文件如下所示:

ITEM1     (string)
ITEM2     (string)
ITEM3     (string)
ITEM4     (string)
ITEM5     (string)
ITEM6     (string)
ITEM7     (string)
ITEM8     (string)
ITEM9     (string)
ITEM10    (string)
1         (INT)
NATHAN    (string)

括号中的内容不会写入文件。 它只是从程序中保存的方式。 我想读取文件并将文本存储在变量中。ITEM1-ITEM10 来自一个名为 inventory[10] 的数组。 数字"1"只是一个标记,位于变量"int gameposition"中。名称"NATHAN"位于字符串"字符串字符名称"中。

文件路径为:

C:apoadventuresavegame.txt

我知道这种类型的保存保存游戏信息不是很聪明,但我对此很陌生,我只是在尝试和学习。

您有一个基于行的格式,因此请使用getline.任何不是字符串的东西都可以从刚刚读取的字符串转换(例如stoi在下面的代码中(

string inventory[10], charactername, work;
int gameposition;
for (int i = 0; i < 10; ++i)
getline(file, inventory[i]);
getline(file, work);
gameposition = stoi(work);
getline(file, charactername);

更新

cout << "Gameposition: " + gameposition << endl;
cout << "Your character: " + selectedChar << endl;

应该是

cout << "Gameposition: " << gameposition << endl;
cout << "Your character: " << selectedChar << endl;

我的输入文件.txt

Apple 1
Mango 2
Banana 3
Grape 4

我的主体

#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::ifstream file;
file.open("InputFile.txt");
std::string str[4];
for (int i = 0; std::getline(file, str[i]);i++) 
{
std::cout << str[i] << "n";
}
file.close();
}

现在在上面的代码中,我使用getline((函数逐行输入.txt文件中的数据。

这是我的输出

Apple 1
Mango 2
Banana 3
Grape 4

希望这可以帮助您如何逐行从文件中输入数据:-(

到目前为止,这部分正在工作。

TXT 文件包含:

ITEM1
ITEM2
ITEM3
ITEM4
ITEM5
ITEM6
ITEM7
ITEM8
ITEM9
ITEM10
0
NATHAN
string savedinv[10], charactername, work;
int gameposition;
ifstream file;
file.open("C:/apoadventure/savegame.txt");
cout << "Inventory loaded:n";
cout << "n";
for (int i = 0; i <= 9; ++i) {
getline(file, savedinv[i]);
cout << savedinv[i] << "n";
}
cout << "n";
getline(file, work);
gameposition = stoi(work);
getline(file, charactername);
selectedChar = charactername;
file.close();
//handling information
//inventory + gameposition + selectedChar
inventory[0] = savedinv[0];
inventory[1] = savedinv[1];
inventory[2] = savedinv[2];
inventory[3] = savedinv[3];
inventory[4] = savedinv[4];
inventory[5] = savedinv[5];
inventory[6] = savedinv[6];
inventory[7] = savedinv[7];
inventory[8] = savedinv[8];
inventory[9] = savedinv[9];

但是当我尝试调用游戏位置时,它没有给我任何回报。

cout << "Gameposition: " + gameposition << endl;
cout << "Your character: " + selectedChar << endl;
cout << "n";

输出:

ITEM1
ITEM2
ITEM3
ITEM4
ITEM5
ITEM6
ITEM7
ITEM8
ITEM9
ITEM10
Gameposition:
Your character: NATHAN