代码之家  ›  专栏  ›  技术社区  ›  r3k0j

在c++中有没有办法将输入字符串转换为输入流?

  •  1
  • r3k0j  · 技术社区  · 2 年前

    我想做的是从终端获取用户输入,并在程序的其他功能中使用该输入。因为我的函数只把输入流作为参数,所以我想把输入字符串转换成输入流。

    int main(int argc, char** argv)
    {
    
        std::vector<std::string> args(argv, argv + argc);
        
        if(args.size() == 1){ //if no arguments are passed in the console
            std::string from_console;
            std::istringstream is;
            std::vector<std::string> input;
            while(!getline(std::cin,from_console).eof()){
                input.emplace_back(from_console);
            }
            for(std::string str : input){
                std::cout << "\n" << str;
            }
    }
    

    在我尝试这段代码时出现的另一个问题是,当我用一堆字符结束控制台输入,而不是用新行(按enter键,然后按ctrl+d)结束时,该行被忽略,没有打印出来。 例子: 当我输入以下内容时:

    aaa bbb
    ccc ctrl+d
    

    我只得到了第一行(aaa bbb),没有打印出来。 但是:

    aaa bbb
    ccc
    ctrl+d 
    

    3 回复  |  直到 2 年前
        1
  •  4
  •   eerorika    2 年前

    在c++中有没有办法将输入字符串转换为输入流?

    是的,这是可能的。这是什么 std::istringstream 是给你的。例子:

    std::string input = some_input;
    std::istringstream istream(input); // this is an input stream
    
        2
  •  1
  •   Adrian Mole Chris    2 年前

    这个 std::istringstream class 有一个构造函数 std::string 作为参数,它使用传递的字符串的副本作为流的初始内容。

    因此,与其使用 std::vector 要存储控制台中的所有输入行,只需将它们添加到单个(不同的)输入行中即可 std::string 对象,记住在每个对象之后添加换行符,然后构造 std::istringstream 从那以后。

    下面是一个简单的例子,展示了如何使用 std::getline (与函数一样,它将输入流作为第一个参数)同样适用于 std::cin 还有 std::istringstream 这样创建的对象:

    #include <iostream>
    #include <sstream>
    
    int main()
    {
        std::string buffer; // Create an empty buffer to start with
        std::string input;
        // Fill buffer with input ...
        do {
            getline(std::cin, input);
            buffer += input;
            buffer += '\n';
        } while (!input.empty()); // ... until we enter a blank line
    
        // Create stringstream from buffer ...
        std::istringstream iss{ buffer };
    
        // Feed input back:
        do {
            getline(iss, input);
            std::cout << input << "\n";
        } while (!input.empty());
    
        return 0;
    }
    
        3
  •  1
  •   Chris HazardXD    2 年前

    当eof与最后一行内容在同一行时, getline(std::cin,from_console) 将到达它并且 .eof() 将返回true,因此最后一行被读入字符串 from_console 但不是推进向量。

    有两种方法:

    1. 通过手动将最后一行推入向量来修改代码:
    while(!getline(std::cin,from_console).eof()){
        input.emplace_back(from_console);
    }
    input.emplace_back(from_console);  // add one line
    for(std::string str : input){
    
    1. iterator 这可能是一种优雅的方式:
    #include <iterator>
    // ...
    if (args.size() == 1) {  // if no arguments are passed in the console
        copy(std::istream_iterator<std::string>(std::cin), {}, 
             std::ostream_iterator<std::string>(std::cout, "\n"));
    }