Break in C ++ by pressing enter

#include <iostream> using namespace std; int main() { int n,t=0,k=0; cin>>n; char data[n][100]; int num[n]; for(int i=0;i<n;i++) { while(1) { cin>>data[i][t]; cout<<data[i][t]<<endl; if(data[i][t]=='\n') break; k++; if(k%2==1) t++; } cout<<i; num[i]=(t-2)/2; k=0; t=0; } for(int i=0;i<n;i++) { while(1) { cout<<data[i][t]; if(t==num[i]) break; t++; } t=0; } } 

here is the code I wrote in C ++ that gives even numbers from the initial half of each word specified by the user, but when input is input after pressing enter, the loop should be interrupted, but the loop is not interrupted

 while(1) { cin>>data[i][t]; cout<<data[i][t]<<endl; if(data[i][t]=='\n') break; k++; if(k%2==1) t++; } 
+5
source share
2 answers

By default, formatted input using "input" operators >> skips a space, and a new line - a space character. So what happens is that the >> operator is just waiting for a non-white space to be entered.

To say that the input does not skip the space, you should use the std::noskipws manipulator:

 cin>>noskipws>>data[i][t]; 
+9
source

There are several ways to implement in C ++ what the OP is trying to do. I would start avoiding Variable Length Arrays that are not standard and use std::string and std::vector instead.

One option is to read the whole line with the input std::getline , and then process the resulting line to save only the first half of the even characters:

 #include <iostream> #include <string> #include <vector> int main() { using std::cin; using std::cout; using std::string; cout << "How many lines?\n"; int n; cin >> n; std::vector<string> half_words; string line; while ( n > 0 && std::getline(cin, line) ) { if ( line.empty() ) // skip empty lines and trailing newlines continue; string word; auto length = line.length() / 2; for ( string::size_type i = 1; i < length; i += 2 ) { word += line[i]; } half_words.push_back(word); --n; } cout << "\nShrinked words:\n\n"; for ( const auto &s : half_words ) { cout << s << '\n'; } return 0; } 

Another, as Joachim Pieleborg did in his answer, disable the passing of leading spaces with formatted input functions using the std::noskipws manipulator and then read char at a time:

 // ... // disables skipping of whitespace and then consume the trailing newline char odd, even; cin >> std::noskipws >> odd; std::vector<string> half_words; while ( n > 0 ) { string word; // read every character in a row till a newline, but store in a string // only the even ones while ( cin >> odd && odd != '\n' && cin >> even && even != '\n' ) { word += even; } // add the shrinked line to the vector of strings auto half = word.length() / 2; half_words.emplace_back(word.begin(), word.begin() + half); --n; } // ... 
0
source

All Articles