我有我的对象的模型类:
class customClass {
string s1;
string s2;
string s3;
}
和文件如下:
text1;text1;text1 text1 text1...
text2;text2;text2 text2 text2...
...
我想要制作对象数组
s1 = "text1"
s2 = "text1"
s3 = "text1 text1 text1..."
...
我的代码:
infile.open("file.txt");
if (infile.is_open())
{
string line;
for (int i = 0; i < 3; i++)
{
infile >> line;
stringstream ss(line);
while (ss.good())
{
string substring;
getline(ss, substring, ';');
cout << substring <<endl;
}
}
}
但它将每个单词分开。如何忽略空格使我的第3个字符串成为文本而不是单个单词。
答案 0 :(得分:0)
它不适合你的原因是因为infile >> line;
将读取第一个空格字符而不是整行(这是你需要getline
时)。也许是这样的:
#include <string>
#include <iostream>
#include <fstream>
int main()
{
std::ofstream outfile("file.txt");
outfile <<
R"(text1;text1;text1 text1 text1...
text2;text2;text2 text2 text2...)";
outfile.close();
// read file
std::ifstream infile("file.txt");
std::string par1, par2, par3;
while (std::getline(infile, par1, ';') && std::getline(infile, par2, ';') && std::getline(infile, par3))
std::cout << par1 << " | " << par2 << " | " << par3 << std::endl;
}
演示:http://coliru.stacked-crooked.com/view?id=eb52001b5d4ecbed
答案 1 :(得分:0)
只是不要在开始时读取单个字符串,我也添加了循环直到文件结束,所以你的代码看起来像:
std::ifstream infile("file.txt");
std::string line;
if (infile.is_open())
{
string line;
while (std::getline(infile, line)) {
std::stringstream ss(line);
string substring;
while (getline(ss, substring, ';')) {
cout << substring <<endl;
}
}
}
答案 2 :(得分:0)
使用getline
函数读取所有行。默认>>
操作获取值\n
,(空格)字符。
#include <iostream>
#include <fstream>
#include <string.h>
#include <sstream>
using namespace std;
class CustomClass
{
public:
string s1;
string s2;
string s3;
};
int main()
{
ifstream infile;
infile.open("test.txt");
if (infile.is_open())
{
while (!infile.eof())
{
string line;
getline(infile, line);
stringstream ss(line);
CustomClass cls;
getline(ss, cls.s1, ';');
getline(ss, cls.s2, ';');
getline(ss, cls.s3, ';');
cout << cls.s1 << " - " << cls.s2 << " - " << cls.s3 << endl;
}
}
return 0;
}