【问题标题】:getline() with delim not working as intended带 delim 的 getline() 无法按预期工作
【发布时间】:2012-08-30 14:58:15
【问题描述】:

我试图用逗号分隔这个字符串作为分隔符。我输入了一个字符串“Smith,Erdos,William”,它只输出“William”,而不是 Smith 和 Erdos。这里一定有什么问题,我只是看不到,有人可以帮忙吗?

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

int main() {
    int numScenarios(0);
    int numPapers(0);
    int numWriters(0);
    std::vector<std::string> paperTitles (1);
    std::vector<std::string> paperAuthors (1);
    std::vector<std::string> splitAuthors (1);
    std::string token;
    std::string input;
    std::cin >> numScenarios;
    std::cin >> numPapers >> numWriters; 
    for (int i(0); i < numPapers; ++i) {
        std::getline(std::cin,input);
        std::istringstream iss(input);
        while(getline(iss,token,','));
        {
            std::cout << token << std::endl;
        }
        //paperTitles.push_back(input);
        //input = '\0';
    }
    for (int i(0); i < numWriters; ++i) {
        getline(std::cin,input);
        paperAuthors.push_back(input);
        input = '\0';
    }


return 0;
}

【问题讨论】:

  • 在相关链接中发现了这个(这是一个你没有解决的问题):stackoverflow.com/questions/2039918/…
  • 您似乎也将一些东西推到了向量的背面,但永远不要使用您在创建过程中放入的那个。

标签: c++ console-application getline split


【解决方案1】:

while(getline(iss,token,',')); // &lt;== look closely

【讨论】:

  • -Wempty-body(包含在-Wextra中)是你的朋友。
  • 虽然在第二次读取时,-Wempty-body 仅警告 ifelsedo...while 语句中的空正文,not for 或常规 @ 987654329@ 语句,所以在这里实际上无济于事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多