【问题标题】:Getline function in C++ is taking first input as the null character. Is it supposed to do that?C++ 中的 Getline 函数将第一个输入作为空字符。它应该这样做吗?
【发布时间】:2017-11-28 17:07:20
【问题描述】:

从第一行输出来看,它似乎将一个空字符作为第一个字符串。也正因为如此,它缺少它应该作为输入的最后一个字符串。我可能会错过 getline 的使用,但我不确定,如果有任何帮助,我们将不胜感激。

int main() {
    short int t,i;
    cin>>t;
    string a;
    while(t–)
    {
        getline(cin,a);
        cout<<"length of string is "<<a.length()<<endl;
        for(i=0;i<a.length()/2;i+=2)
        { 
            cout<<a[i];
        }
        cout<<endl;
    }
    return 0;
}  

输入

4 你好 理解 思考 编程

输出

字符串长度为 0 字符串长度为 5 H 字符串长度为 10 udr 字符串长度为 5 吨

【问题讨论】:

  • 在您执行cin&gt;&gt;t; 之后,缓冲区仍包含换行符序列,然后由getline() 读取。
  • 看看右边的相关问题。

标签: c++ getline


【解决方案1】:

执行cin&gt;&gt;t; 后,缓冲区仍包含换行符序列。然后getline() 立即读取一个换行符,使其认为用户只是按下了回车键而没有输入任何内容。

为了解决这个问题,您需要在调用 getline() 之前忽略换行符。

【讨论】:

  • 你的意思是消耗换行符?你会怎么做?
  • @machine_1 查看cin.ignore() 的文档。我很确定这个问题之前已经在 Stack Overflow 上得到了回答。既然我已经解释了问题,我建议您进行更多搜索。
【解决方案2】:

当您调用cin&gt;&gt;t 时,它会在到达非数字字符时停止读取,从而将换行符留在cin 的缓冲区中。随后的std::getline() 读取该换行符并返回一个空白字符串。

所以,您需要:

  • 在调用cin&gt;&gt;t 后调用cin.ignore() 以删除该换行符:

    #include <string>
    #include <iostream>
    #include <limits>
    
    int main()
    {
        short int t;
    
        std::cin >> t;
        std::cin.ignore(std::numeric_limits<std::streamize>::max(), '\n'); // <-- add this!
    
        while (t-– > 0)
        {
            std::string a;
            std::getline(std::cin, a);
            std::cout << "length of string is " << a.length() << std::endl;
            for (std::string::size_type i = 0; i < (a.length() / 2); i += 2)
            { 
                std::cout << a[i];
            }
    
            std::cout << std::endl;
        }
    
        return 0;
    }
    
  • 使用std::getline() 读取t 的行,然后使用std::istringstream 从该行解析t 的值:

    #include <string>
    #include <iostream>
    #include <sstream>
    
    int main()
    {
        short int t;
        std::string a;
    
        std::getline(std::cin, a);
        std::istringstream(s) >> t;
    
        while (t-– > 0)
        {
            std::getline(std::cin, a);
            std::cout << "length of string is " << a.length() << std::endl;
            for (std::string::size_type i = 0; i < (a.length() / 2); i += 2)
            { 
                std::cout << a[i];
            }
    
            std::cout << std::endl;
        }
    
        return 0;
    }
    

【讨论】:

    猜你喜欢
    • 2013-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-15
    • 1970-01-01
    相关资源
    最近更新 更多