Jump to content

Program not working correctly

- - - - -

  • Please log in to reply
6 replies to this topic

#1
snorifu

snorifu

    Newbie

  • Members
  • Pip
  • 7 posts
Hello,
I just made this program but it doesn't work the way I want.
[B]#include <iostream>

#include <stdlib.h>

using namespace std;

int main()

{

    int a;

    cout << "How many names?:";

    cin >> a;

    char name [a][10];

    int ra[a];

    for (int i=0;i<a;i++){

        cout << "name"<<i<<"?:";

        cin.getline (name [i],10);

        }

    for (int i=0;i<a;i++){

            ra[i]=rand() %100+1;

        }

    for (int i=0;i<a;i++){

    cout << name[i] << ":" << ra[i] << "\n"

        }

    cin >> ra[1];

}

[/B]
The problem is that if I execute the code I can't enter name0 it seems to jump directly to name 1.
Can anybody help with this?

#2
lintwurm

lintwurm

    Learning Programmer

  • Members
  • PipPipPip
  • 77 posts
This program works as expected.
Not sure what is wrong with yours though, sorry...

#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
	int a;
	cout << "How many names?:";
	cin >> a;
	char name [a][10];
	int ra[a];
	for (int i=0;i<a;i++){
		cout << "name"<<i<<":";
		cin>>name[i];
	}
	for (int i=0;i<a;i++){
		ra[i]=rand() %100+1;
	}
	for (int i=0;i<a;i++)
	{
		cout << name[i] << ":" << ra[i] << "\n";
	}
	cin >> ra[1];
}


#3
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
The carriage return on your i=0 may be causing it to read in name[0] as an empty string.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#4
cocoa10

cocoa10

    Newbie

  • Members
  • PipPip
  • 12 posts
This is just a though, because it worked for me, copy your posted code and try running it.

#5
snorifu

snorifu

    Newbie

  • Members
  • Pip
  • 7 posts

WingedPanther said:

The carriage return on your i=0 may be causing it to read in name[0] as an empty string.
Is a carriage return the same as newline?
I don't see a newline sorry.
This is the output:

Posted Image

#6
brownhead

brownhead

    Programmer

  • Members
  • PipPipPipPip
  • 173 posts
I think wingedpanther is right. When your program takes in that 3, there's still a newline in the buffer (cause you hit enter after you put that 3 in didn't you?). You can call cin.get() if you'd like, which would take in a single character from the buffer. Or you could call cin.seekg(0, ios_base::end) which would place the get pointer at the end of the buffer, skipping whatever else is in the buffer.

#7
snorifu

snorifu

    Newbie

  • Members
  • Pip
  • 7 posts
Ok thanks cin.get() did the trick:)




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users