逐行从文本文件中读取 |C++
reading from a textfile line by line | C++
我现在在互联网上搜索了一段时间,但找不到适合我的解决方案。 或者我只是哑巴。 我在一个.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
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 无法找到/读取配置文件.conf-FileIOException
- 如何使用Luacneneneba API正确读取字符串和表参数
- C++将文本文件中的数据读取到结构数组中
- 正在将csv文件读取为双精度矢量
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 为什么在读取文件大小时文件IO速度会发生变化
- 正在读取二进制文件(is_open)
- 如何在c++中从文本文件中逐行读取整数
- SSH通过/sbin/SSH无法读取RSA密钥文件(从控制台运行)
- 独立读取-修改-写入顺序
- 从文本文件中读取时钟时间和事件时间并进行处理
- 如何从文本文件中读取值和数组
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 一种在C++中读取TXT配置文件的简单方法