简体   繁体   中英

How do I get character by character input in c++?

First I need to read two integers N & Q separated by space. I am doing this using cin. Then in next two lines two binary numbers each of N digits follow. I am trying to read these numbers bit by bit using getchar() and putting them into int vector but it is printing garbage values. Is there a problem with new line character. I know I could first read them into a string and then put them into vector but I wanted to do this way. Here is my code:

#include <iostream>
#include <algorithm>
#include <vector>
#include <stdio.h>
using namespace std;
int main(){
    int N;
    int Q;
    cin >>N>>Q;
    string A, B;
    //cin >> A>>B;
    vector <int> Abit;
    vector <int> Bbit;

    for (int i=0;i<N;i++){
        char c= (int) getchar();
        Abit.push_back(c);
    }
    for (int i=0;i<N;i++){
    //  cout << Abit.at(i);
        char c= (int) getchar();
        Bbit.push_back(c);
    }
    for (int i=0;i<N;i++){
        cout << Abit.at(i);
    //  char c= (int) getchar();
    //  Bbit.push_back(c);
    }
}

You can just simply do it by reading a character.

char c;
for ( int i = 0; i < N; ++i ){
  cin >> c;
  Abit.push_back(c);
}
for ( int i = 0; i < N; ++i ){
  cin >> c;
  Bbit.push_back(c);
}

the >> operator will avoid any form of seprate, space, new line, etc.

Each time you type a character and press return, getchar will be called twice - the first time for the character you input, and the second time for the '\\n' character. So, if you input 1 2 3 4 5 , you will push back in your vector the following: 10, 49, 10, 50, 10 .

The first 10 if for the remained \\n character from the cin << N << Q; call.

The other 49 stands for the ASCII 1 , and the 50 for the ASCII 2 .

You may want to read entire line into the string, and then to extract the characters out from the string. Of course, you still need to to convert ASCII characters to integers, but you can do that by subtracting the character value from the value of ASCII 0 : c - '0' .

Also, you can remove ignore all before and including newline by reading them before the actual digit:

 while(getchar() != '\n');
 char c= (int) getchar() - '0';

Better way, which would skip all newlines before digit is suggested by Charlie Burns . Tou just need to read all newline characters before the actual digit:

    char c;
    while((c = getchar()) == '\n');
    Abit.push_back(c - '0');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM