【发布时间】:2021-10-25 07:52:35
【问题描述】:
我正在使用 (getline(MyFile, line)) 从文本文件中读取文本文件,并希望将其存储在每个元素的字符串数组中。 我的代码无法正常工作。 基本上,我需要从文件中读取,将每一行保存到一个字符串数组中,然后在每个元素处遍历每个字符串。 for 循环也没有增加到 4,我不知道为什么。请帮忙。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int array[16], i;
fstream myFile;
string filename, line, str[256];
int main() {
// 1. The user will enter the full name of the file
cout << "Enter the file name to open: ";
cin >> filename;
getchar(); // clear the input buffer before reading the filename
// 2. Open the file for reading (input)
myFile.open(filename.c_str(), fstream::in);
// only continue if the file has opened successfully
if (myFile.is_open() == false) {
cout << "ERROR: not able to open " << filename << endl;
}
else {
// 3. Access the file - read all the lines from the file
for (i = 0; i < 5; i++) {
while (getline(myFile, line)) {
str[i] = line;
cout << "String [" << i << "] = " << str[i] << endl;
}
}
}
}
【问题讨论】:
-
问问自己:当 i == 0 时读取了多少行?在调试器下运行程序,在
str[i] = line上设置断点,看看会发生什么。
标签: c++ arrays for-loop iteration getline