조해인
조해인

Reputation: 19

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

string nums;

int main() {
  int cases;
  scanf("%d", &cases);
  while (cases--) {
    cin.ignore();
    getline(cin, nums);
    cout << nums << endl;
  }
}

input example

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

I expect right result below

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

However, the output is that

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

I don't know what the reason is. I clearly use cin.ignore() to flush the buffer. Why is the first char removed ?

Upvotes: 0

Views: 68

Answers (2)

cse
cse

Reputation: 4104

Just put the line cin.ignore(); outside the while loop:

Following is corrected code. See it working here:

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;
}

Upvotes: 2

Justin Randall
Justin Randall

Reputation: 2278

You should initialize your cases to 0 just in case a user enters an invalid input for an integer type like a character or something. You should prefer to use std::cin for user input in C++ like I stated in the comments section. You can skip the \n newline character after your initial input by calling get(). It's serving the same purpose as you were trying to achieve with ignore(). while(cases--) is a bit weird to look at but I get what you're going for. You can declare your string nums inside the loop since you're overwriting it every iteration anyway. The reason you do not need to use std::cin.ignore() in this code is because std::getline reads everything including the newline character from console input. This code should do exactly what you want.

#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;
}

Upvotes: 0

Related Questions