Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Getting string input from cin - cleanly

Status
Not open for further replies.

azarc

Programmer
Apr 14, 2003
12
0
0
US
Hi,

I am fairly new to C++ and am struggling somewhat with keeping control of a simple console program that needs to extract input from cin (I want to keep to the Standard Library).

I am attempting to find an elegant way to extract strings from the console using the Microsoft V6 and Borland V5.5 compilers. I would like to have as much control as the C# Console.ReadLine().

I have come across a bug in the Microsoft Standard library which seems to rule out the simple solution of just using the string getline (
Here is the code I have come up with - it seems a clunky way to do it,

#include <iostream>
#include <string>

using namespace std;

const int MAX_STRING_LENGTH = 255;

/*
Microsoft libraries define _MSC_VER = 1200 for C++ compiler version 6
Borland libraries define __BORLANDC__
*/
class ConsoleInput
{

public:

#ifdef _MSC_VER

static string getStringLine()
{
char inputChar[MAX_STRING_LENGTH];
cin.getline(inputChar, MAX_STRING_LENGTH, '\n');
return inputChar;
}
#else
static string getStringLine()
{
string inputString;
getline(cin, inputString);
return inputString;
}
#endif

};

int main()
{
while(true)
{
cout << &quot;Press q to quit or any key to continue => &quot;;

string inputString = ConsoleInput::getStringLine();

cout << inputString << endl;

if( inputString[0]== 'q')
break;
}

return 0;
}

Aaron
 
This solution came either from a previous posting or another forum. For MSVC, if you open up the string #include file, you'll find this statement or something very similar

else if (_Tr::eq(_C, _D))
{_Chg = true;
_I.rdbuf()->snextc();
break; }

Replace the line

_I.rdbuf()->snextc();

With

_I.rdbuf()->sbumpc();

then you can use

getline(cin, inputString);
 
Thanks for that.

Problem is that will fix it for my machine but is no good if I am distributing source for compilation on other machines.

Probably the best solution is to note the bug in the source code comments telling people to fix it if they want the program to run properly.

Thanks,

Aaron
 
That doesn't sounds like a &quot;best&quot; solution for anyone. Programmers risk breaking their own existing code to get yours to work. Non-programmers won't want to have to mess with stuff like that.

Unfortunately, I think the &quot;cleanest&quot; way is to just use the #ifdef stuff and provide a workaround for faulty libraries.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top