我已经有了这段代码,由于某种原因,cin.get没有为p.name [i]分配值。我不知道为什么,但是getline也不起作用。我试图只是cin.get(temp,30)来读取一个临时文件,但这在for循环中不起作用。

#include <iostream>
#include <string>
using namespace std;

typedef struct echip
{
    char name[30];
    double price;
};

void read(echip* p, int n)
{

    for (int i = 0; i < n; i++)
    {
        cout << "Name: ";

        cin.get((p + i)->name, 30);
        cin.ignore();

        cout << (p + i)->name;

        cout << "Price: "; cin >> (p+i)->price;
        cout << (p+i)->price;
    }
}

int main()
{
    echip* k;
    int n;

    cout << "Number: "; cin >> n;
    k = new echip[n];

    read(k, n);

    delete[] k;
    return 0;
}

最佳答案

cin.ignore()放在cin.get()之前:

Live demo

#include<limits>
//...

for (int i = 0; i < n; i++)
{
    cout << "Name: ";
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); //here
    cin.get((p + i)->name, 30);

    cout << (p + i)->name;
    cout << "Price: ";

    cin >> (p+i)->price;
    cout << (p+i)->price;
}
cin.get()与带有运算符cin>>不同,不会忽略换行符。

我认为需要提及的其他一些小问题:
  • 在C++中,struct不需要是typedef'd。
  • C++具有标准容器,可以代替C样式的容器使用,在这种情况下, std::string 是一个不错的选择。
  • Using namespace std; is not considered a good practice
  • 09-25 17:45
    查看更多