【问题标题】:Char array in struct cuts out first letter结构中的字符数组删除了第一个字母
【发布时间】:2012-11-01 04:46:25
【问题描述】:

我刚刚开始学习 C++,在整个指针/数组章节中,我试图编写一些代码来掌握这些概念。我想要我的代码做的是:1)询问一些学生,2)询问每个学生的名字,3)在结构中为这个学生分配一个 ID 和名字,4)打印学生 ID 和名字进行验证。

问题如下。 例如,假设我选择输入 3 个学生并输入以下名称:

JOHN
GEORGE
NICK

程序打印回的学生 ID/姓名将是:

0 JOHN
1 EORGE
2 ICK

似乎把所有名字的第一个字母都删掉了,除了第一个。

#include <iostream>
using namespace std;

struct STUDENT
{
char chName[256];
int nID;
};

int main(){

//array tests

int i=0;
int nLoops=0;                   //number entered by user
STUDENT *pnStudents;            //pointer to our student array

cout << "Enter number of students: ";
cin >> nLoops;

pnStudents = new STUDENT[nLoops];

for (i=0 ; i < nLoops ; i++)
{
    cout << endl << "Full Name of Student " << i <<": ";
    cin.ignore();
    cin.getline(pnStudents[i].chName,255);

    pnStudents[i].nID=i;
}

for (i=0 ; i < nLoops ; i++)
{
    cout << pnStudents[i].nID << " " << *pnStudents[i].chName << endl;
}

system("pause");

return 0;
}

【问题讨论】:

  • 我强烈建议尽早学习使用调试器。

标签: c++ arrays char


【解决方案1】:
for (i=0 ; i < nLoops ; i++)
{
    cout << endl << "Full Name of Student " << i <<": ";
    cin.ignore();
    cin.getline(pnStudents[i].chName,255);

    pnStudents[i].nID=i;
}

在循环的第一次迭代中,ignore() 提取cin &gt;&gt; nLoops; 调用留在流中的换行符。另一方面,istream::getline() 会丢弃尾随的 '\n',因此每次后续迭代都会等待并丢弃您输入的第一个字符。

在循环之前移动cin.ignore()

【讨论】:

    【解决方案2】:

    cin.ignore(); 不带参数丢弃来自 cin 的大小为 1 的流。

    istream& 忽略 (streamsize n = 1, int delim = EOF);

    提取和 丢弃字符从输入序列中提取字符并 丢弃它们。

    删除它。这似乎是你的代码中唯一可以吃掉一个字符的东西。另外,如果您需要使用忽略,请使用以下内容:

    cin.ignore(256,' ');
                ^   ^   (number of char, delim)
    

    如果您试图忽略作为nLoops 输入的字符,则无需在每次迭代中都这样做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多