#include<iostream>
//#include<cstring>
#include<string>
using namespace std;
//const int max = 10;
struct PizzaData {
string brand;
float diameter;
float weight;
};
int main() {
PizzaData *p = new PizzaData[3];
for (int i = 0; i<3; i++) {
cout << "The brand of the pizza company:";
getline(cin, (p + i)->brand);
//cin.get();
cout << "The diameter is:";
cin >> p[i].diameter;
cout << "The weight of the pizza is:";
cin >> (p + i)->weight;
}
for (int j = 0; j<3; j++) {
cout << "The brand of the pizza company is:" << p[j].brand;
cout << " and it is " << p[j].diameter << " centimeters and has " << p[j].weight << " kilograms." << endl;
}
delete[] p;
p=NULL;
system("pause");
return 0;
}

只能成功給結構體陣列的第一個成員賦值,后面再我輸入了第二組成員的brand元素后就不給我輸入,并且錯誤顯示
uj5u.com熱心網友回復:
你是想要這種效果???我用vscode跑出來好像沒有什么問題,代碼附上,為了測驗改了一些,整體沒變,你對照一下?struct PizzaData
{
string brand;
float diameter;
float weight;
};
PizzaData *p = new PizzaData[3];
for (int i = 0; i < 3; i++)
{
cout << "The brand of the pizza company:";
cin >> p[i].brand;
//getline(cin, (p + i)->brand);
//cin.get();
cout << "The diameter is:";
cin >> p[i].diameter;
cout << "The weight of the pizza is:";
cin >> p[i].weight;
}
for (int j = 0; j < 3; j++)
{
cout << "The brand of the pizza company is:" << p[j].brand;
cout << " and it is " << p[j].diameter << " centimeters and has " << p[j].weight << " kilograms." << endl;
}
delete[] p;
p = NULL;
uj5u.com熱心網友回復:
我在vs2015上運行,但總是在for回圈賦值的第二個物件那里,一輸入brand值回車就自動給我后面的物件賦值了uj5u.com熱心網友回復:
找到問題所在了,是關于getline(cin,string)的使用問題,我試著用了簡單的cin輸入流,然后就能夠完整輸出了。uj5u.com熱心網友回復:
不過這樣的輸入只針對單個單詞的輸入,如果輸入有空白隔開的字串,就會出現空白(空格符、換行符)滯留在輸入流中,并且在執行后面的輸入陳述句時輸出給后面的元素物件。簡單來說,就是無法處理成行的輸入,本來我使用getline就是為了能夠輸入(big one)這樣的字串的,簡單用cin無法達到更進一步的效果。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/247771.html
標籤:C++ 語言
