輸入:aa aa,導致后面無法輸入,且無法正常顯示,尤其是回圈3.原因是什么?
我知道是cin的緣故,但是不理解為什么是cin。我改成cin.getline,又會有產生新的問題。

代碼:
// structur.cpp -- a simple structure
#include <iostream>
#include <cstring>
struct inflatable // structure declaration
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
inflatable guest =
{
"Glorious Gloria", // name value
1.88, // volume value
29.99 // price value
}; // guest is a structure variable of type inflatable
// It's initialized to the indicated values
inflatable pal =
{
"Audacious Arthur",
3.12,
32.99
}; // pal is a second variable of type inflatable
// NOTE: some implementations require using
// static inflatable guest =
cout << "Expand your guest list with " << guest.name;
cout << " and " << pal.name << "!\n";
// pal.name is the name member of the pal variable
cout << "You can have both for $";
cout << guest.price + pal.price << "!\n";
// cin.get();
// my structure array test
inflatable guest_array[3];
for (int i = 0; i < 3; i++)
{
cout << "Please input name: " << endl;
// cin.getline(guest_array[i].name, 20);
cin >> guest_array[i].name;
cout << "Please input volume: " << endl;
cin >> guest_array[i].volume;
cout << "Please input price: " << endl;
cin >> guest_array[i].price;
cout << "name: " << guest_array[i].name << endl;
cout << "volume: " << guest_array[i].volume << endl;
cout << "price: " << guest_array[i].price << endl;
}
return 0;
}
uj5u.com熱心網友回復:
每輸入一個資料,就按下回車uj5u.com熱心網友回復:
截圖中回圈3不理解是怎么回事。
uj5u.com熱心網友回復:
你除錯一下就知道了uj5u.com熱心網友回復:
就是因為除錯不明白才發帖的
uj5u.com熱心網友回復:
不考慮這個問題了,我在另一個帖子中搞清了“c++如何保證輸入始終是數字而不是字符”,回圈輸入數字或者字符才是我的目的。https://bbs.csdn.net/topics/396698161
最終代碼:
// my_structur.cpp -- 創建結構體陣列,回圈輸入結構體元素。
// 1 創建結構體;
// 2 創建結構體陣列;
// 3 回圈輸入結構體元素時保證始終輸入字串或數字;
// 3.1 while (1) {}
#include <iostream>
#include <cstring>
struct inflatable // structure declaration
{
char name[20];
float volume;
double price;
};
int main()
{
using namespace std;
// my structure array test
inflatable guest_array[3];
for (int i = 0; i < 3; i++)
{
cout << "Please input name: " << endl;
// cin.getline(guest_array[i].name, 20);
// cin>> noskipws >> guest_array[i].name;
cin.get(guest_array[i].name, 20);
cout << "Please input volume: " << endl;
while (!(cin >> guest_array[i].volume))
{
cout << "無效輸入! 請重新輸入數字:" << endl;
cin.clear();
cin.ignore(1024, '\n');
}
// while (!scanf("%d", &guest_array[i].volume) || guest_array[i].volume < 0)
// {
// printf("無效輸入!請重新輸入:\n");
// scanf("%*[^\n]");
// scanf("%*c");
// }
cin.get();
cout << "Please input price: " << endl;
cin >> guest_array[i].price;
cin.get();
cout << "name" << i << ": " << guest_array[i].name << endl;
cout << "volume: " << guest_array[i].volume << endl;
cout << "price: " << guest_array[i].price << endl;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/54990.html
標籤:C++ 語言
