#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;
int main(){
char string1 [50] {};
char string2 [50] {};
cout << "enter the string 1: ";
cin.get(string1,50);
cout << "your string1: " << string1 << endl;
cout << "enter the string 2: ";
cin.get(string2,50);
cout << "your string2: " << string2 << endl;
cout << strcmp(string1, string2);
return 0;
}
How to use strcmp()
wit string1
(with space) and string2
(with space)?
What I've tried:
Input:
abc def
Output:
your string1: abc def
enter the string 2: your string2:
1
The result that I want:
Input:
abc def
abc def
Output:
0
Here's the issue:
cin.get(string1,50);
reads up to 49 characters or until it encounters a \n
but it doesn't consume the \n
.
When cin.get(string2,50);
is reached the \n
from the first line is the first character in the input buffer so nothing is read.
There's a few ways I can think of to fix this.
\n
. If more than 49 characters were entered on a line the ignore
would cause the 50th character to be lost.cin.getline
does consume the \n
. If more than 49 characters were entered on a line this wouldn't lose any characters, it would read from 50 to 99 or until a \n
was reached.There are some other small differences with error handling that don't affect your code as written but you might review the linked documentation for each to decide which is best.
Here's an example using cin.getline
that gives the output you expect.
Output:
enter the string 1:
your string1: 'abc def'
enter the string 2:
your string2: 'abc def'
0
It's slightly different from your original code since I added single quotes around the string and a couple of newlines to make it a little more readable and help to validate what was going on.