這個問題在這里已經有了答案: 如何將 cin'd c 樣式字串傳遞給函式? (2 個回答) 昨天關門。
這是我的代碼我期待輸出但我沒有得到
你的名字叫嚴酷
#include <iostream>
#include <cstring>
using namespace std;
int main() {
cout << "Enter your name" << endl;
char *s;
cin >> s;
cout << "Your name is " << s;
return 0;
}
我也嘗試過,cin.getline(s,100);但仍然無法正常作業。所以我請求你解決問題并給我解決方案。
uj5u.com熱心網友回復:
您的代碼具有未定義的行為,因為您沒有分配任何記憶體s來指向。s是一個未初始化的指標。
試試這個:
#include <iostream>
using namespace std;
int main(){
cout << "Enter your name" << endl;
char s[100];
cin >> s; // or: cin.getline(s,100);
cout << "Your name is " << s;
return 0;
}
或者,您應該std::string改用,例如:
#include <iostream>
#include <string>
using namespace std;
int main(){
cout << "Enter your name" << endl;
string s;
cin >> s; // or: getline(cin,s);
cout << "Your name is " << s;
return 0;
}
uj5u.com熱心網友回復:
s 在您的代碼中未分配。
由于我們說的是 C ,你可能不想使用指標和記憶體分配,std::string而是使用。
#include <iostream>
#include <string>
using namespace std;
int main ()
{
cout << "Enter your name" << endl;
string s; // Instead of dealing with char* allocation and memory issues.
cin >> s;
cout << "Your name is " << s;
return 0;
}
uj5u.com熱心網友回復:
你做對了,但輸出的問題是因為記憶體分配。您必須分配記憶體并盡量避免其中的指標概念。而是使用 string s; 或字符s[50];
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/415834.html
標籤:
上一篇:關于堆和作用域
