473,399 Members | 4,192 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Taking strings with spaces as input and storing into class data member.

11
Hello,

I am writing a program in which I take a string (specifically, first and last name with a space in between) from the user and put it into a data member of a class node. I have tried various things, but to no avail.

I am using using Borland Turbo C++ 2005 on XP Professional SP2.

My includes for both methods:
Expand|Select|Wrap|Line Numbers
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <fstream>
  4. #include <string>
  5. #include <stdlib>
  6. using namespace std;
  7.  
This first method compiles OK, but does not wait for user input, and skips right to the next line...
Expand|Select|Wrap|Line Numbers
  1. void CEmployee::AddEmp()    //user defined class and member function
  2. {
  3.    CEmployee *pCurr;
  4.    std::string name;
  5.  
  6. //m_Name, m_Age, and m_pHead are CEmployee data members
  7.    pCurr = new CEmployee;
  8.    pCurr->m_pLink = m_pHead;
  9.    m_pHead = pCurr;
  10.  
  11.    cout << "Enter Employee Name: ";
  12.    cin.getline(pCurr->m_Name, 20, '\n');
  13.  
  14.    cout << "Enter Employee's Age: ";
  15.    cin >> pCurr->m_Age;
  16.  
  17.  //rest of program follows
This compiles fine, but the output is wrong; the program does not wait for user input before moving on to [cout << "Enter Employee's Age: ";]. Nor does it put [cout << "Enter Employee's Age: ";] onto a new line (as I would expect).

Output:

Enter Employee Name: Enter Employee's Age: [waits for input here]

I also tried the following (based on advice I saw in another post regarding spaces in strings), and it wouldn't even compile:

Expand|Select|Wrap|Line Numbers
  1. void CEmployee::AddEmp() 
  2. {
  3.    CEmployee *pCurr;
  4.    std::string name;
  5.  
  6.    pCurr = new CEmployee;
  7.    pCurr->m_pLink = m_pHead;
  8.    m_pHead = pCurr;
  9.  
  10.    cout << "Enter Employee Name: ";
  11.    std::getline(std::cin, name, 20, '\n');
  12.    pCurr->m_Name = name;      
  13.  
  14.    cout << "Enter Employee's Age: ";
  15.    cin >> pCurr->m_Age;
  16.  
  17. //rest of program follows
  18.  
  19.  
This generated two compiler errors:
1) Could not find a match for 'std::getline<_Elem,_Traits,_Alloc>(istream, string, int, char)

This error is obviously in reference to [std::getline(std::cin, name, 20, '\n')]

2) Lvalue required

This is in reference to <pCurr->m_Name = name;>

Please help. I am having a hell of a time figuring this out!
Thanks in advance.
Mar 14 '08 #1
8 3298
weaknessforcats
9,208 Expert Mod 8TB
The first thing the >> operator does is to check to see of the input stream in in a fail state. If it is, it just returns without doing anything so your program just races on like there were no cin >> statement inthe code.

Nowhere do I see to check to see of the >> failed:

Expand|Select|Wrap|Line Numbers
  1.  
  2. cin >> something
  3. if (cin.fail() )
  4. {
  5.     //oops...
  6. }
  7.  
You need to check every cin >>.

If you are in a fail state, then cin.clear() will reset the failbit but the offending data will still be in the input stream. You will need to flush the stream or extract data using means other than the >> operator to clear the bad data.
Mar 14 '08 #2
yomama
11
The first thing the >> operator does is to check to see of the input stream in in a fail state. If it is, it just returns without doing anything so your program just races on like there were no cin >> statement inthe code.

Nowhere do I see to check to see of the >> failed:

Code: ( cpp )

cin >> something
if (cin.fail() )
{
//oops...
}



You need to check every cin >>.

If you are in a fail state, then cin.clear() will reset the failbit but the offending data will still be in the input stream. You will need to flush the stream or extract data using means other than the >> operator to clear the bad data.
Thanks for the reply.
Note that the problem I'm having in the first scenario is at line 12:

cin.getline(pCurr->m_Name, 20, '\n');

This is the line at which that C++ fails to wait, and here i do not explicitly call >> with cin. Does getline() implicitly call >> ?

For what it's worth, I tried sticking the following after line 12:
Expand|Select|Wrap|Line Numbers
  1.    if (cin.fail())
  2.         cout << "cin failed, bro.";
  3.  
C++ did not print that statement, and skipped to the next line, this time with a '\n'

Output:
Employee Name:
Employee Age: [waits for input here]

It's also worth mentioning that today with the same code I was using last night (and without the cin.fail check), my program did wait for input at line 12, but then barfed when I entered a string (either with or without a space). It acted just like it would if I entered a char when it as expecting an int.

Not sure what is going on here...
Mar 14 '08 #3
Laharl
849 Expert 512MB
Try using >> to fix your problem with getline(). To fix the error with spaces, use quotes (" ") to surround your whole string, as items on the input stream are delimited by any form of whitespace.

For example:
Expand|Select|Wrap|Line Numbers
  1. string name;
  2. cout << "Enter name: ";
  3. cin >> name;
  4. cout << name;
  5.  
Sample output:
Enter name: Joe Jones
Joe

Enter name: "Joe Jones"
Joe Jones
Mar 14 '08 #4
yomama
11
Try using >> to fix your problem with getline(). To fix the error with spaces, use quotes (" ") to surround your whole string, as items on the input stream are delimited by any form of whitespace.

For example:
Code: ( cpp )

1.
string name;
2.
cout << "Enter name: ";
3.
cin >> name;
4.
cout << name;



Sample output:
Enter name: Joe Jones
Joe

Enter name: "Joe Jones"
Joe Jones
Doing that allows line 12 to stop for input (as expected), but doesn't take the whole string. My debugger shows that the first ", J, o, and e, are assigned to the first four elements of my array. Then the fifth element points to 0. The following three elements are assigned t, x, 2, and point to some random memory addressed. Every remaining element of my array thereafter points to NULL.

The remaining characters from the cin (i.e. , J, o, n, e, s, and ") are then stuck in the buffer, and cause my program to go into what appears to be an inifinite loop, while it tries to figure out what to do with them.
Mar 14 '08 #5
Laharl
849 Expert 512MB
Hrm, you're right. I guess you do have to use getline(). Look up strtok() if you need specific parts of the input line.
Mar 14 '08 #6
yomama
11
Hrm, you're right. I guess you do have to use getline(). Look up strtok() if you need specific parts of the input line.
Thanks. I'll make learning more about strtok() my next order of business. My current understanding of strtok(), though, is that it is used to stop reading input at a certain point (e.g. some delimiter) rather than to continue reading input at a certain point (which is what I want to do here), but I'll investigate it some more once this pesky work day is up.
Mar 14 '08 #7
Studlyami
464 Expert 256MB
when you first call strtok you tell where to start looking and what your looking for. Then on the second call you pass NULL in for the location and it will continue where it left off from the last call.
Mar 14 '08 #8
yomama
11
Got it figured out, everyone. I had an enter press stuck in the buffer from a previously called function that I needed to discard. Once I did that, cin.getline() worked like a charm.

Thanks for the help!
Mar 15 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: SophistiCat | last post by:
Hi, I am working on a computational program that has to read a number of parameters (~50) from an input file. The program contains a single class hierarchy with about a dozen member-classes or...
3
by: googleboy | last post by:
Hi there. I have defined a class called Item with several (about 30 I think) different attributes (is that the right word in this context?). An abbreviated example of the code for this is: ...
17
by: tommy | last post by:
Hi all, I' m adding strings to some fields in my table via Access. The strings sometimes have trailing spaces and I really need to have it that way, but Access truncates trailing spaces. How can...
89
by: scroopy | last post by:
Hi, I've always used std::string but I'm having to use a 3rd party library that returns const char*s. Given: char* pString1 = "Blah "; const char* pString2 = "Blah Blah"; How do I append...
4
by: Steve Carter | last post by:
The following code fragment prompts the user to enter two integers separated by a space. It works the way I want it to, but a friend said it's not correct and said it can cause a buffer overflow. I...
13
by: Superman859 | last post by:
Hello everyone. Heads up - c++ syntax is killing me. I do quite well in creating a Java program with very few syntax errors, but I get them all over the place in c++. The smallest little things...
5
by: alan | last post by:
Hello world, I'm wondering if it's possible to implement some sort of class/object that can perform mapping from class types to strings? I will know the class type at compile time, like so:...
14
by: Karch | last post by:
I need to find the fastest way in terms of storage and searching to determine if a given string contains one of a member of a list of strings. So, think of it in terms of this: I have a string such...
10
by: DeveloperDave | last post by:
Hi, I am trying to improve some code that I currently have. I have a simple class called RequestMessage e.g. class RequestMessage { public: RequestMessage();
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.