我在阅读和使用数据文件时遇到了一些麻烦。我将从数据文件中创建3个类别。前两个类别均基于保证不会被拆分的数据。第三类可分为可变次数 下面的代码是我目前使用的过程。当每个段只是一个部分时(例如,段3 ="狗"),这就完成了工作,但我需要应用程序能够处理段3的可变数量的部分(例如,segment3 =& #34;金毛猎犬"或者半金半鹦鹉")。 segment1和segment2保证是完整的,不在空格之间分割。我理解为什么我的代码会跳过任何多余的空格(而不是记录" Golden Retriever"它只会记录" Golden"。我不知道如何操纵我的代码,以便它理解segment2之后的行中的任何内容都是segment3的一部分。
______________________________
// This is the structure of the data file. It is a .txt
China 1987 Great Wall of China.
Jordan 1985 Petra.
Peru 1983 Machu Picchu.
// End of Data file. Code below.
________________________________
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int main()
{
ifstream myFile("data.txt");
string segment1;
string segment2;
string segment3;
vector <string> myVec;
while(myFile >> segment1 >> segment2 >> segment3)
{
vector <string> myVec; //
myVec.push_back(segment1); myVec.push_back(segment2); myVec.push_back(segment3);
int Value = atoi(myVec[1].c_str()); // should print int value prints zero with getline
}
return 0;
}
我已经搜索了stackoverflow和互联网,并找到了一些想法,但在使用我的代码时似乎没有任何帮助解决问题。 我所拥有的最好的想法将涉及废弃我当前读取文件的方法。 1.我可以使用getline解析数据并将其解析为向量。 我可以将索引0分配给segment1,将索引1分配给segment2。 3.我可以将索引3分配到矢量到段3的末尾。
Galik的解决方案帮助我解决了这个问题,但现在我在尝试输入强制转换时遇到了问题。 [int altsegment2 = atoi(segment2.c_str());]现在总是导致零
答案 0 :(得分:3)
您可以使用std::getline来读取整个行的其余内容:
#include <iostream>
#include <fstream>
#include <sstream> // testing
#include <vector>
using namespace std;
int main()
{
// for testing I substituted this in place
// of a file.
std::istringstream myFile(R"~(
China 1987 Great Wall of China.
Jordan 1985 Petra.
Peru 1983 Machu Picchu.
)~");
string seg1;
string seg2;
string seg3;
vector<string> v;
// reads segments 1 & 2, skips spaces (std::ws), then take
// the rest of the line into segment3
while(std::getline(myFile >> seg1 >> seg2 >> std::ws, seg3))
{
v.push_back(seg1);
v.push_back(seg2);
v.push_back(seg3);
}
for(auto const& seg: v)
std::cout << seg << '\n';
return 0;
}
<强>输出:强>
China
1987
Great Wall of China.
Jordan
1985
Petra.
Peru
1983
Machu Picchu.