我在显示寄存器中输入的数据时遇到问题。我编写的以下程序仅显示最后一个寄存器。( ziua=day , inregistrari=registers, data=date (ex. 03.02.2013))
#include <iostream>
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
char ziua[30],data[30],inregistrari[90];
int n,i;
cout<<"INPUT DATA"<<endl;
system("Pause");
cout<<"\nEnter the day in which you want to perform the register: ";
cin>>ziua;
cout<<"\nDATE:";
cin>>data;
cout<<"\nEnter the number of registers you wanna perfom for the day "<<ziua<<":";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"\nRegister "<<i<<":";
gets(inregistrari);
}
cout<<"The data for the day of "<<ziua<<" are the following: ";
cout<<"\nDATE: "<<data;
for(i=1;i<=n;i++)
cout<<"\n"<<inregistrari;
getch();
}
最佳答案
- 你正在用 C++ 编程,你应该使用
std::string
而不是 C 风格的字符串。 -
inregistrari[90]
是一个字符数组,大到足以容纳 1 个最大长度为 89 的字符串char
s(+ 终止字符),但您的循环似乎将其视为数组或字符串(尽管在这种情况下gets(inregistrari);
继续重写相同的字符串) - 函数
gets
通常不推荐使用,在 C 中你应该使用fgets
相反(但这是 C++,因此这里真正的解决方案应该使用std::getline
) - 使用
std::vector<std::string>
而不是 C 风格的数组在这里。 - 打印
inregistrari
在for
的正文中循环,但此循环的每次迭代都做完全相同的事情(打印不以任何方式依赖于i
) -
using namespace std;
在全局空间内是一种不好的做法 - 您不必在函数的开头声明所有变量,这在旧的 ANSI C 中是必需的(大约 20 年前)
这是一个例子,它看起来像这样:
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::string day, date;
int registerCount;
std::cout << "INPUT DATA"
<< std::endl << std::endl
<< "Enter the day in which you want to perform the register: "
<< std::endl;
std::cin >> day;
std::cout << "DATE:" << std::endl;
std::cin >> date;
std::cout << "Enter the number of registers you wanna perfom for the day "
<< day << ":" << std::endl;
std::cin >> registerCount;
std::vector<std::string> registers(registerCount);
for (int i = 0; i < registerCount; ++i)
{
std::cout << "Register " << i << ":" << std::endl;
std::getline(std::cin, registers[i]);
}
std::cout << "The data for the day of " << day << " are the following: "
<< std::endl;
std::cout << "DATE: " << date << std::endl;
for (int i = 0; i < registerCount; ++i)
std::cout << registers[i] << std::endl;
}
请注意,您可能会将 std::getline(std::cin, registers[i])
换行与 if
声明并检查是否已返回有效的流对象,如果是空行,它将读取空字符串,因此您还可以确保 !registers[i].empty()
.
关于c++ - 带有字符显示的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18615387/