Home > OS >  how to compare (strcmp) 2 char with space?
how to compare (strcmp) 2 char with space?

Time:11-09

#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

CodePudding user response:

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.

  1. Keep using cin.get and add a cin.ignore() after the first read to consume the \n. If more than 49 characters were entered on a line the ignore would cause the 50th character to be lost.
  2. Switch to using cin.getline with the same parameters. The difference is that 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.

  1. If you are able to I strongly encourage using std::string for your variables and std::getline to read the data. The advantage to this is that you don't need to worry about specifying an explicit length. The amount of data that is provided will be read and the string resized to fit it. This would help to close the loophole where more than 49 characters were supplied on a line.

Here's an example using cin.getline that gives the output you expect.

Demo

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.

  • Related