Pkzzz
Pkzzz

Reputation: 111

C++: how to read the user input using a c-string two times?

I want to input

1 2
3 4 5

a: 1 2 b: 3 4 5 If I use this way, I will get b is also 1 2, I tried cin.ignore(), it doesn't work. Here is my code:

#include <iostream>
#include <string>

using namespace std;

int main(){
   char a[3];
   char b[5];   
   cin>>a;
   cin>>b;
   cout<<b[0]<<endl; 
   return 0;
}  

Upvotes: 0

Views: 57

Answers (1)

asmmo
asmmo

Reputation: 7100

You can use a loop to read an array of characteres and to stop that loop, choose some character as a mark (but you will have to use Enter after it) or use EOF which can be occur by ctrl+d on linux or ctrl+z on windows, as follows

#include <iostream>

int main(){
    char a[50];//to hold an array of 49 chars
    int i{};
    char end {'a'};//non space char
    while( std::cin >> a[i] && a[i] != end)
        i++;

    a[i] = '\0';
    std::cout << a << std::endl;
    return 0;
}

Or use std::getline(). It's better. You won't need a thing but an Enter

#include <iostream>
#include <string>
int main(){
    char a[50];
    std::string temp{};
    std::getline(std::cin, temp);
    int i{ -1 };
    while( ++i < temp.size()) a[i] = temp[i];
    a[i] = '\0';
    std::cout << a << std::endl;
    return 0;
}

Upvotes: 1

Related Questions