这是一个有点重复的问题,因为我认为我有足够的答案来找到我需要的地方。结果我没有。我有一个 .txt 文件,格式如下,
It is certain
positive
You may rely on it
positive
.
.
.
Very Doubtful
negative
我需要获取此文本文件并将其分成两个单独的数组,一个用于响应,一个用于类别。到目前为止,我已经能够使用 getline 将 .txt 文件分成两个字符串,但我似乎无法将它放入一个数组中。
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main(){
int size = 20;
int i = 0;
string responses[size];
string categories[size];
string line1, line2;
ifstream infile("responses.txt");
if(infile.is_open())
{
//input
while(getline(infile, line1) && getline(infile, line2))
{
//cout << line1 << endl;
//cout << line2 << endl
getline(infile, line1) >> responses[i];
getline(infile, line2) >> categories[i];
cout << responses[i] << endl;
cout << categories[i] << endl;
++i;
}
infile.close();
}else
{
cout << "File not open" << '\n';
}
return 0;
}
我对上面的代码进行了几次不同的迭代和更改,但这是最近的一次。在此先感谢您的帮助或指导。非常感谢这位编程菜鸟。
最佳答案
如果你知道这两个数组的大小(responses.txt 中的行数),试试这个
for(int i=0; i<size_array; i++){
getline(infile, responses[i]);
getline(infile, categories[i]);
}
getline(infile, line1)
会将 responses.txt 中的当前行获取到 line1,你不需要在 while() 代码中再次调用 getline()。
如果您不知道 responses.txt 中有多少行,请考虑使用 std::vector
而不是普通数组。
std::vector<std::string> responses, categories;
while(getline(infile, line1) && getline(infile, line2)){
responses.push_back(line1);
categories.push_back(line2);
}
关于c++ - 将输入 txt 文件中比单个单词长的字符串存储到两个单独的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53172725/