Kevin
Kevin

Reputation: 65

My c++ program terminated without taking the input.What should i do?

The code below,works fine but it does not take any value for age and terminates.`

#include <iostream>
#include <string>
using namespace std;
class user{
    int id,level=1,kills=0,age;
    char name[20],server[40];
public:

void get(){
    cout<<"Enter your name:";
    cin>>name[20];
    cout<<"Enter your age:";
    cin>>age;

}
};
int main(){
    user u;
    u.get();
    return 0;
}
/*Output
Enter your name:Jack
Enter your age:
C:\Users\user\documents\c++
*/

In the output section ,age is not accepted and the program terminates.

Upvotes: 3

Views: 1257

Answers (4)

M Umer
M Umer

Reputation: 413

The easiest way to handle strings (a long sequence of characters) or even the strings that have spaces just use the following library in C++.

#include <bits/stdc++.h>

Then just declare a string variable.

String name;

Now you can save a very long string without any error. e.g.

name = jshkad skshdur kslsjue djsdf2341;

and you'll get no error, enjoy ;)

Upvotes: 0

Klaus
Klaus

Reputation: 25623

Your problem is here:

    cin>>name[20];

Why:

'name[20]' is 21th char of the array you defined before. It counts from 0! As this, it is simply a single char. If you now enter more than a single char, the rest is read by the cin>>age.

Example:

    cout<<"Enter your name:";
    cin>>name[20];
    cout<<"Enter your age:";
    cin>>age;

    std::cout << "Name " << name << std::endl;
    std::cout << "Age " << age << std::endl;

And entering:

Enter your name:1234
Enter your age:Name 
Age 234

As you see, the '1' is now in the name and the rest is stored in age.

But attention: You defined your array as `name[20], which means you have 0..19 elements. Accessing name[20] is wrong!

But what you simply want to do was:

cin >> name;

Upvotes: 1

Yash Mishra
Yash Mishra

Reputation: 19

Use string name instead of char name[20] to take multi-character value. char name[20] will terminate after taking a single character.

Also, its valued will not be displayed on giving output.

Modified code for reference.

#include <iostream>
#include <string>
using namespace std;
class user{
    int id,level=1,kills=0,age;
    string name,server;
public:

void get(){
    cout<<"Enter your name:";
    cin>>name;
    cout<<"Enter your age:";
    cin>>age;
}

//test output
void put(){
    cout<<name<<endl;
    cout<<age<<endl;
}
};
int main(){
    user u;
    u.get();
    //test
    u.put();
    return 0;
}

Upvotes: 2

Anish B.
Anish B.

Reputation: 16529

Just modify the code to this :

#include <iostream>
#include <string>
using namespace std;
class user{
    int id,level=1,kills=0,age;
    char name[20],server[40];
public:

void get(){
    cout<<"Enter your name:";
    cin>>name; // changes done here
    cout<<"Enter your age:";
    cin>>age;

}
};
int main(){
    user u;
    u.get();
    return 0;
}

Job Done :)

Upvotes: 1

Related Questions