使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中

first char is not stored in a string object using getline() function of string header in c++

本文关键字:字符串 第一个 char 对象 函数 存储 使用 getline      更新时间:2023-10-16
string nums;
int main() {
  int cases;
  scanf("%d", &cases);
  while (cases--) {
    cin.ignore();
    getline(cin, nums);
    cout << nums << endl;
  }
}

输入示例

3
1 2 1 2 1
2 3 4 1 2 5 10 50 3 50
3 5 2 7 1 7 5 2 8 9 1 25 15 8 3 1 38 45 8 1

我希望在

下方正确的结果
1 2 1 2 1
2 3 4 1 2 5 10 50 3 50
3 5 2 7 1 7 5 2 8 9 1 25 15 8 3 1 38 45 8 1

但是,输出是

1 2 1 2 1
 3 4 1 2 5 10 50 3 50
 5 2 7 1 7 5 2 8 9 1 25 15 8 3 1 38 45 8 1

我不知道原因是什么。我显然使用cin.ignore()冲洗缓冲区。为什么要删除第一个字符?

只需将行cin.ignore();放在while循环外:

以下是更正的代码。在这里看到它:

string nums;
int main() 
{
    int cases;
    scanf("%d", &cases);//Better if you use `cin>>cases;` here, just for sake of C++.
    cin.ignore();
    while (cases--) 
    {
        getline(cin, nums);
        cout << nums <<endl;
    }
    return 0;
}

您应该初始化 cases至0,以防用户输入无效的整数输入,例如字符或其他东西。您应该更喜欢将std::cin用于C 中的用户输入,就像我在评论部分中所述。您可以通过调用get()在初始输入后跳过n Newline字符。它的目的与您尝试实现ignore()相同的目的。while(cases--)看来有些奇怪,但我明白了您的目标。您可以在循环内声明您的string nums,因为您无论如何都会覆盖它。您不需要在此代码中使用std::cin.ignore()的原因是因为std::getline读取所有内容,包括控制台输入中的newline字符。此代码应该完全做您想要的。

#include <iostream>
#include <string>
int main()
{
    int cases(0);  ///< initialize in case user enters text
    (std::cin >> cases).get(); ///< use std::cin in C++; get() to skip `n`
    while (cases--) ///< is that really what you want?
    {
        std::string nums; ///< nums only needed locally
        std::getline(std::cin, nums); ///< reads whole line + 'n'
        std::cout << nums << std::endl;
    }
    return 0;
}