C++从文件中读取文本并将其存储在独立的变量

问题描述:

我的.txt文件是这样的:C++从文件中读取文本并将其存储在独立的变量

question1 answer1 
question2 answer2 
question3 answer3 

我怎样才能把question1answer1成两个独立的变量?我可以使用getLine(),但它会返回问题和答案。

+0

问题和答案之间的分隔符是什么? – fritzone 2014-08-27 18:53:56

+0

为什么不使用getline,然后使用逻辑来区分两者? – Conduit 2014-08-27 18:55:37

+0

没有这样的函数'getLine()',你的意思是'getline()'吗?此外,流有'operator >>'解析空白分隔的令牌。这可能是你想使用的。如果*需要*使用'getline()',则将该字符串放在'std :: istringstream'中,并使用'operator >>'。 – 0x499602D2 2014-08-27 18:57:00

如果每个问题用一个问号终止,则你可以写

std::string line; 

while (std::getline(FileStream, line)) 
{ 
    std::istringstream is(line); 

    std::string question; 
    std::string answer; 

    std::getline(is, question, '?'); 
    question += '?'; 
    std::getline(is, answer); 

    // some processing of question and answer 
} 

如果使用一些其他的分隔符,那么你需要替换问号这种分离器,也许删除线

question += '?'; 
+0

非常感谢,这就是我需要的! – Mil 2014-08-28 13:58:23