Question

Friends, I want to read a pair of characters separated by \t. I want to continue reading the input until user enters z for any of the characters.

Here are the options I thought:

while (cin>>ch1>>ch2)
{

// process ch1 & ch2

}

std::string str;

while (getline(cin, str) ){

//split string

}

Also, I want to validate the input to make sure that it is correct. Please suggest the best way. If this is a duplicate, please point me to the right one.

Thanks.

Was it helpful?

Solution

Despite its name, you can use std::getline() to read other things than lines. It takes an optional third parameter denoting the delimiter. The default one is '\n', but there's no reason you cannot use '\t' instead.

std::string line;
while( std::getline(is,line) ) { // read lines
  std::istringstream iss(line); 
  std::string field;
  while( std::getline(iss,field,'\t') { // read fields from line
    // process field
  }
}

OTHER TIPS

Your first approach is good and very C++ish. The only problem is that it will read chars not only separated by \t, but also, for example, by plain space ();

The code would look the following way:

#include <iostream>

void main () {
   char c1, c2;
   while (std::cin >> c1 >> c2) {
      if (c1 == 'z' || c2 == 'z') break;
      // Otherwise do something useful
   }
}

Alternative approach is using getche() to take one symbol from input and show it on the screen. Here's the code:

#include <iostream>
#include <conio.h>

void main () {
   while (true) {
      char c1 = getche();
      char delimiter = getche();
      char c2 = getche();

      // Output end of line
      std::cout << std::endl;

      if (delimiter != '\t' || c1 == 'z' || c2 == 'z') break;
      // Otherwise do something useful
   }
}

Note that right now you don't have to press enter key after entering sequence. If you want to, you could add one more getche() call and check if the char equals 32 (enter code).

int main(int argc, char* argv[])
{
    char c;
    int count = 0;
    string s; // s.reserve(LOTS);
    while(cin) while( cin.get(c) ) { // consume newlines as well
        if( c == '\t' ) continue;
        if( c == 'z' ) break;
        ++count;
        s += c;
    }
    cout << "got " << count << " tokens." << endl;
    cout << s << endl;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top