首页 文章

将字符串对象强制转换为istringstream

提问于
浏览
1
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>

void reverse_words(const std::string &file) {
    std::ifstream inFile { file };
    std::vector<std::string> lines;
    if(static_cast<bool>(inFile)) {
        std::string line;
        while(std::getline(inFile, line, '\n')) {
                lines.push_back(line);
        }

    std::vector<std::string> reverse_line;
    std::string word;
    for(auto line: lines) {
        while(std::getline(line, word, ' '))
            reverse_line.push_back(word);

    }

    }
}

int main(int argc, char ** argv) {
    if(argc == 2) {
        reverse_words(argv[1]);
    }
}

在我的程序的最后一个for循环中,我想从一行中读取一个单词,该行是一个字符串,因此这与getline()函数定义不匹配 . 如何将线转换为字符串流,以便我可以像文件一样使用它进行读取?

请忽略该程序的逻辑,它不完整,我的问题是C具体的 .

2 回答

  • 0

    你只需构造一个istringstream

    for(auto const& line: lines) {
        std::istringstream iss{line};  // <-------
        while(std::getline(iss, word, ' ')) {
            reverse_line.push_back(word);
        }
    }
    
  • 2
    std::string s("hello world");
    std::istringstream ss(s);
    std::string s1, s2;
    ss >> s1 >> s2;
    std::cout << s1 << std::endl;
    std::cout << s2 << std::endl;
    

相关问题