c++ - C++ 中的 Getline 函数将第一个输入作为空字符。它应该这样做吗?

标签 c++ getline

从第一行输出来看,它似乎将空字符作为第一个字符串。也正因为如此,它丢失了它应该作为输入的最后一个字符串。我可能错过了 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
hello
understand
think
programming

输出

length of string is 0
length of string is 5
h
length of string is 10
udr
length of string is 5
t

最佳答案

执行cin>>t; 后,缓冲区仍包含换行符序列。然后 getline() 立即读取一个换行符,这会欺骗它认为用户只是按下了 enter 键而没有输入任何内容。

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

关于c++ - C++ 中的 Getline 函数将第一个输入作为空字符。它应该这样做吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47537195/

相关文章:

C++ c2664 错误 "cannot convert argument 1 from std::string to _Elem *"

c - 将 getline() 输出保存到外部数组

C++ Getline 并不总是在 Linux 中的多个 fork 进程中获取行

c++ - 使用重载的 new 和 delete 运算符跟踪已用内存?

c++ - 从原始指针构造时 shared_ptr 是否分配?

c++ - 简单的 'keypress' 程序

C++ DLL 函数导出。 DLL 不会保持加载状态

c++ - 使用 QT 处理来自 C 程序的数据的 GUI

c++ - C++中线程读取文件

C 将大文件读入 char* 数组太慢