我在显示寄存器中输入的数据时遇到问题。我写的下面的程序只显示最后一个寄存器。(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();
}
答案 0 :(得分:3)
std::string
而不是C风格的字符串。inregistrari[90]
是一个字符数组,大小足以容纳1个字符串,最大长度为89 char
s(+终止字符),但您的循环似乎将其视为数组或字符串(虽然在这种情况下gets(inregistrari);
继续重写相同的字符串)gets
通常已被弃用,在C中你应该使用fgets
代替(但这是C ++,因此这里真正的解决方案应该是使用std::getline
)std::vector<std::string>
。inregistrari
位于for
循环的主体中,但此循环的每次迭代都完全相同(打印不依赖于i
)< / LI>
全球空间内的using namespace std;
是一种不好的做法以下是一个例子:
#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()
。