簡體   English   中英

我的c ++程序在沒有輸入的情況下終止。我該怎么辦?

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

下面的代碼工作正常,但它不會對年齡有任何價值並終止

#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++
*/

在輸出部分,不接受年齡,程序終止。

使用string name而不是char name[20]來獲取多字符值。 char name [20]將在獲取單個字符后終止。

此外,它的值不會在給出輸出時顯示。

修改代碼供參考。

#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;
}

只需將代碼修改為:

#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;
}

任務完成 :)

你的問題在這里:

    cin>>name[20];

為什么:

'name [20]'是您之前定義的數組的第21個字符。 它從0開始計算! 因此,它只是一個字符。 如果您現在輸入多個char,其余的則由cin>>age讀取。

例:

    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;

進入:

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

如您所見,'1'現在在名稱中,其余的存儲在年齡中。

但注意:你將數組定義為`name [20],這意味着你有0..19個元素。 訪問名稱[20]是錯誤的!

但你只想做的是:

cin >> name;

處理字符串(一長串字符)或甚至包含空格的字符串的最簡單方法是在C ++中使用以下庫。

#include <bits/stdc++.h>

然后只聲明一個字符串變量。

String name;

現在您可以保存很長的字符串而不會出現任何錯誤。 例如

name = jshkad skshdur kslsjue djsdf2341;

你會得到沒有錯誤,享受;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM