Clearing CIN/COUT

I was trying to make a simple program that would accept strings of input then ignore any input after a delimiting character.

I've probably misinterpreted the format of the documentation here:
http://www.cplusplus.com/reference/istream/istream/getline/

I would like to accept two strings of input, and anything after the character 'X' just gets ignored/flushed/deleted or whatever the proper term is.

Then I'd like to be able to print out via COUT the result of the truncated input.

Sounds so complicated when I write it out but it looks really simple. Here is the code.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main () {
  char text_1[256], text_2[256];

  std::cout << "Please enter some text for Line 1. Everything after the character 'X' will be ignored: ";
  std::cin.getline (text_1,256,'X');
  std::cin.clear();
  std::cout << "Please enter some text for Line 2. Everything after the character 'X' will be ignored: ";
  std::cin.getline (text_2,256,'X');
  std::cin.clear();
  std::cout << "Line 1's split text is: " << text_1 << "\n";
  std::cout << "Line 2's split text is: " << text_2 << "\n";
  return 0;
}


oh, the problem is the COUT is priting the split input string. It's kind of weird.
Like if I entered on line one "Hello X World"
and I entered on line two "Good X Day"

The output would be

1
2
3
Line 1's split text is: Hello 
Line 2's split text is:  World
Good
Last edited on
cin.clear() does not empty the buffer, it resets any error flags on the stream.
http://www.cplusplus.com/reference/iostream/ios/clear/

use cin.ignore() to extract and discard data from the stream
http://www.cplusplus.com/reference/iostream/istream/ignore/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main() {
	char text_1[256], text_2[256];

	std::cout << "Please enter some text for Line 1.\n"; 
	std::cout << "Everything after the character 'X' will be ignored: ";
	std::cin.getline(text_1, 256, 'X');
	std::cin.ignore(256,'\n');
	std::cout << "Please enter some text for Line 2.\n";
	std::cout << "Everything after the character 'X' will be ignored : ";
	std::cin.getline(text_2, 256, 'X');
	std::cin.ignore(256,'\n');
	std::cout << "Line 1's split text is: " << text_1 << "\n";
	std::cout << "Line 2's split text is: " << text_2 << "\n";
	return 0;
}


This will work ...
Last edited on
Thank you, it makes a lot more sense now.

I wasn't quite sure which to use (ignore or clear) but seeing ignore now I understand I can use a delimiter with ignore also.

Big thanks :D
Last edited on
Topic archived. No new replies allowed.