473,395 Members | 1,577 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,395 software developers and data experts.

Getline and for Loops

here is the code i been playing around with


Expand|Select|Wrap|Line Numbers
  1. using namespace std;
  2. const int COLS = 5;
  3. void initializeArray( int [][COLS], int);
  4.  
  5. int main(int argc, char *argv[])
  6. {
  7.     const int ROWS = 3;
  8.  
  9.  
  10.  
  11.  
  12.  
  13.     int scores [ROWS][COLS];
  14.     string names[ROWS];
  15.     initializeArray(scores, ROWS);
  16.  
  17.     for (int i = 0; i < ROWS; i++)
  18.     {
  19.         names[i] = "";
  20.     }
  21.  
  22.  
  23.     for (int i = 0; i < ROWS; i++)
  24.     {
  25.         for (int j = 0; j < COLS; j++)
  26.         {
  27.             cout << scores[i][j] << " ";
  28.         }
  29.         cout << endl;
  30.  
  31.     }
  32.     cout << endl;
  33.     // fill the array
  34.     for (int i = 0; i < ROWS; i++)
  35.     { 
  36.         cout << "Name: " << names[i];
  37.         getline(cin,names[i]);
  38.         cout << "Please enter " << names[i] << " scores: ";
  39.  
  40.         for (int j = 0; j < COLS; j++)
  41.         {
  42.                 cin >> scores[i][j];
  43.  
  44.         }   
  45.  
  46.     }
  47.     //print
  48.     for (int i = 0; i < ROWS; i++)
  49.     {
  50.         cout << names[i] << " : ";
  51.         for (int j = 0; j < COLS; j++)
  52.         {
  53.             cout << scores[i][j] << " ";
  54.         }
  55.         cout << endl;
  56.  
  57.     }
  58.     cout << endl;
  59.  
  60.     system("PAUSE");
  61.     return EXIT_SUCCESS;
  62. }
  63. void initializeArray( int in[][COLS], int size)
  64. {
  65.     for (int i = 0; i < size; i++)
  66.     {
  67.         for (int j = 0; j < COLS; j++)
  68.         {
  69.             in[i][j] = 0;
  70.         }
  71.     }
  72. }
its a program that you enter a students name then you enter scores in array. i cant seem to find out why it wont let me enter the 2nd name?? the scores work fine. Can anybody help??? thanks
Oct 16 '07 #1
8 4291
Ganon11
3,652 Expert 2GB
This is a problem with C++, so I'll move it to the C++ / C Forum.
Oct 16 '07 #2
Ganon11
3,652 Expert 2GB
There are 2 things I see wrong with this code:

1) You're outputting the contents of scores before you give them any values, so this is going to clutter up your output screen with garbage values.

2) You're using a mixture of getline and cin >> statements, which always leads to the following problem:

When cin is inputting normally (i.e. cin >> scores[i]), it looks for some characters surrounded by whitespace. When it finds this, it inputs the characters, gets rid of the first whitespace, and leaves the last whitespace character there. So, after you input all the scores, there is a newline character ('\n') still there.

When getline is inputting, it looks for any number of characters (including 0) before a newline character ('\n') and returns those characters - it then eats the newline character (so that another getline call will work as expected).

In your situation, you cin >> several times, and when you're done, there is a '\n' still in the input stream. When getline is called, it finds that newline character, thinks, "Cool, I'm done." and returns what characters it found - which is none!

In order to fix this, you need to get rid of that newline character - either by calling cin.get() with a garbage character variable, or with a call to cin.ignore().

EDIT: Oh, I just saw your initializeArray method. So the scores array will have all 0s. Still, I see no reason to print there (except to check that your function worked correctly).
Oct 16 '07 #3
There are 2 things I see wrong with this code:

1) You're outputting the contents of scores before you give them any values, so this is going to clutter up your output screen with garbage values.

2) You're using a mixture of getline and cin >> statements, which always leads to the following problem:

When cin is inputting normally (i.e. cin >> scores[i]), it looks for some characters surrounded by whitespace. When it finds this, it inputs the characters, gets rid of the first whitespace, and leaves the last whitespace character there. So, after you input all the scores, there is a newline character ('\n') still there.

When getline is inputting, it looks for any number of characters (including 0) before a newline character ('\n') and returns those characters - it then eats the newline character (so that another getline call will work as expected).

In your situation, you cin >> several times, and when you're done, there is a '\n' still in the input stream. When getline is called, it finds that newline character, thinks, "Cool, I'm done." and returns what characters it found - which is none!

In order to fix this, you need to get rid of that newline character - either by calling cin.get() with a garbage character variable, or with a call to cin.ignore().

EDIT: Oh, I just saw your initializeArray method. So the scores array will have all 0s. Still, I see no reason to print there (except to check that your function worked correctly).

yea i had the 0 to check if it works but i know its works withthe scores. but what im having problems with is the name.


I ask user to enter name: (user enters "john bert")
Then i ask enter scores(5): (user enters "12 23 34 45 56")
I want to aske for second name but it wont let me it skips the name and goes right into scores again. so i put scors again.


Im supose to have 3 names and 3 rows of scores:

Looks like this:

John bert: 12 23 34 45 56
:32 43 54 65 77
:44 45 56 67 86

when it should be:

John bert: 12 23 34 45 56
jones smith:32 43 54 65 77
robert jon :44 45 56 67 86
Oct 18 '07 #4
oler1s
671 Expert 512MB
Reread Ganon's reply. He explains why inputting the name is skipped over.

When you use cin, you don't clear the entire stream buffer. There's a newline left over because it's clearly not a number. Unfortunately, when you use getline, it picks up on this stray newline and returns. So you do get a name. It's '\n'. Not what you want.

The solution is to either use getline consistently. For the numbers, use getline to grab all the numbers in one go, and then use a stringstream to parse out each number individually.

The other option is to dump the contents of the buffer after using cin. cin.ignore or cin.sync (I think) will do the trick.
Oct 18 '07 #5
Reread Ganon's reply. He explains why inputting the name is skipped over.

When you use cin, you don't clear the entire stream buffer. There's a newline left over because it's clearly not a number. Unfortunately, when you use getline, it picks up on this stray newline and returns. So you do get a name. It's '\n'. Not what you want.

The solution is to either use getline consistently. For the numbers, use getline to grab all the numbers in one go, and then use a stringstream to parse out each number individually.

The other option is to dump the contents of the buffer after using cin. cin.ignore or cin.sync (I think) will do the trick.
oh damn im sorry i totally skipped that whole paragraph he wrote dont know how that happened lol thanks both of u
Oct 18 '07 #6
ok i fixed the skipping the the name part witht he getline ignore. but now i cant figureout y int he first name i enter it cuts off the first letter?

when i run it i get this

eter smith: 1 2 3 4 5
peter smith: 1 2 3 4 5
peter smith: 1 2 3 4 5

when it should be
peter smith: 1 2 3 4 5
peter smith: 1 2 3 4 5
peter smith: 1 2 3 4 5

it only appears how it suppose to when i enter it like this.

It askes me Name: (I enter) (spacebar )Peter smith

how do i fix it so that it works when i just enter it and dont need to press spacebar? Sorry im new with c++ and trying to get a hold of this.
Oct 18 '07 #7
Ganon11
3,652 Expert 2GB
I'm assuming you are using cin.get() as suggested? Put it directly after the cin >> statements, rather than before the getline statement.
Oct 18 '07 #8
I'm assuming you are using cin.get() as suggested? Put it directly after the cin >> statements, rather than before the getline statement.
great thanks.. you the man! now i gotta get to creating functions lol this should be fun. thanks for the help guys
Oct 18 '07 #9

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

Similar topics

2
by: Vikram | last post by:
Hi, I don't remember if it happened previously, but nowadays I'm having problem with using cin.getline function and cin>> function simultaneously. I have Visual Studio 6. If I use cin.getline...
5
by: vknid | last post by:
Hello, I have a question. Its probably a very newbish question so please be nice hehe. =D I have been reading through C++ Programming Fundamentals, and have come a crossed an example program...
1
by: ma740988 | last post by:
Consider: ifstrem MyFile("extractMe.txt"); string Str; getline(MyFile, Str); getline above extracts the contents of MyFile and place into the string object. Deduced using FROM/TO logic I...
10
by: Skywise | last post by:
I keep getting the following error upon compiling: c:\c++ files\programs\stellardebug\unitcode.h(677) : error C2664: 'class istream &__thiscall istream::getline(char *,int,char)' : cannot convert...
14
by: KL | last post by:
I am so lost. I am in a college course for C++, and first off let me state I am not asking for anyone to do my assignment, just clarification on what I seem to not be able to comprehend. I have a...
18
by: Amadeus W. M. | last post by:
I'm trying to read a whole file as a single string, using the getline() function, as in the example below. I can't tell what I'm doing wrong. Tried g++ 3.2, 3.4 and 4.0. Thanks! #include...
2
by: jalkadir | last post by:
I am trying to get character string from the user, to do that I use getline(char_type*, streamsize), but I get a segmentation fault??!! Can anyone give me a hand, what am I doing wrong? --snip...
33
by: Chen shuSheng | last post by:
I have a code: --------------------------- #include <iostream.h> #include <stdlib.h> int main() { int max=15; char line; getline(line,max); system("PAUSE");
13
by: Rosario | last post by:
do you like the "GetLine_m" function i have written today? How many errors do you see? i have try only the option for to load the all file in a string not the option to load a line "\n" ended so...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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:
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
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...

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.