Comp Sci Cin.ignore remove first character

  • Thread starter Thread starter anonim
  • Start date Start date
  • Tags Tags
    C++
Click For Summary
SUMMARY

The discussion centers on the use of cin.ignore() in C++ to manage input when switching from numeric input to string input. Users reported that after using cin.ignore(), the program incorrectly reads input, specifically capturing only part of the string. The solution presented involves removing cin.ignore() before the getline() function, which resolved the issue of capturing the entire input string correctly. This adjustment ensures that the input buffer is properly managed between different types of input.

PREREQUISITES
  • Understanding of C++ input/output streams
  • Familiarity with cin and getline() functions
  • Basic knowledge of control structures in C++
  • Experience with handling user input in console applications
NEXT STEPS
  • Research the behavior of cin.ignore() in C++ input handling
  • Learn about input buffer management in C++
  • Explore alternatives to cin.ignore() for input handling
  • Study common input/output pitfalls in C++ programming
USEFUL FOR

C++ developers, programming students, and anyone troubleshooting input issues in console applications.

anonim
Messages
39
Reaction score
2
Homework Statement
-
Relevant Equations
-
Code:
if(count%2==0){ //for user 1
  cout<<"User 1"<<endl;
  cout << "Please enter your move: ";
  cin.ignore();
  getline(cin,str);
  //do something
}
else if (count%2!=0){ //for user 2
  cout<<"User 2"<<endl;
  cout << "Please enter your move: ";
  cin.ignore();
  getline(cin,str);
  //do something
}
Let's say move is A 2. When first time enter input, It read the 'A 2'. But otherwise it reads ' 2'. How can I fix this?
 
Physics news on Phys.org
Does removing cin.ignore() do what I think you want?

Output.png
 
Joshy said:
Does removing cin.ignore() do what I think you want?

View attachment 272313
Before this part, I was getting numbers elsewhere using cin. And I add cin.ignore after that and I deleted cin.ignore before getline and it fixed. I'm just seeing your answer, but thank you anyway.
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 7 ·
Replies
7
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 9 ·
Replies
9
Views
3K