Hi everyone,

I have not done C++ for quite sometime now and seems that i may have forgotten a bit so please bear with me a while.

I am currently trying to output some text to the console in c++, but seems i may have forgotten something because the text does not output correctly. It is incorrect because each time there is a space in the string only the first string is printed to the console.

This is the code

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <strings.h>
#include <stdio.h>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])

string a;
string b = "This is a test string";
int c = 0, d = 0;

cout<< "Input a string\n";

cin>> a;

d = a.compare(b);

if(d == 0)
cout<< "Both the strings are the same\n";
cout<< "The below is string a\n";
//The below is where the problem occurs if the string is
//the same and only the word "This" is printed
//to the console

cout<< a
cout<<  "\n";
cout<< "The below is string b\n";
cout<<  b;
cout<<  "\n";

cout<< "Both the the strings are different\n";
cout<< "The below is string a\n";
cout<<  a;
cout<<  "\n";
cout<< "The below is string b\n";
cout<<  b;
cout<<  "\n";

return 0;

I am currently using DevC++.

Looks like i have become a bit rusty, please bear with me on this question.

Any help is greatly appreciated

Thank You

Yours Sincerely

Richard West

Recommended Answers

All 3 Replies

Change cin>>a ; to getline(cin,a); and remove #include <strings.h> and #include <stdio.h>

Why getline, and not cin for such a simple application?

Is getline a better option for string manipulation or something?

The >> will stop input into the desired variable at the first white space char it encounters. Whitespace characters include the space, tab, and newline char in addition to EOF indicator.

getline(), whether the version for C style strings or the version for STL strings won't stop at any whitespace char. It will stop at the designated char, which is the newline char by default, but can be any char you wish.

getline() is a member of the iostream class as is the >> operator. Therefore it's not getline() vs cin but getline() vs >>. Both getline() and the >> operator are overloaded in the STL string class so they can be used with STL strings in a very similar fashion to what they are used otherwise.

In the example posted the only files needed are the iostream and string headers. IF you want to include some of the older C style files AND your compiler is namespace compliant, then you would be better off using the updated C header files, which all start with the letter c and don't have the .h extension. So it would be cstdlib instead of stdlib.h and cctype instead of ctype.h and cstdio instead of stdio.h, etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.