c++ - vector with characters displaying -
i have problem displaying data entered in register. folowing program wrote displays last register.( 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 day in want perform register: "; cin>>ziua; cout<<"\ndate:"; cin>>data; cout<<"\nenter number of registers wanna perfom day "<<ziua<<":"; cin>>n; for(i=1;i<=n;i++) { cout<<"\nregister "<<i<<":"; gets(inregistrari); } cout<<"the data day of "<<ziua<<" following: "; cout<<"\ndate: "<<data; for(i=1;i<=n;i++) cout<<"\n"<<inregistrari; getch(); }
- you programming in c++, should use
std::string
instead of c-style strings. inregistrari[90]
array of characters big enough hold 1 string of max length of 89char
s (+ terminating character), loop seems treating array or strings (although in casegets(inregistrari);
keeps on rewriting same string)- function
gets
deprecated, in c should usefgets
instead (yet c++, real solution here should usingstd::getline
) - instead of c-style arrays, use
std::vector<std::string>
here. - printing
inregistrari
in body offor
loop, each iteration of loop same thing (the printing not depend oni
in way) using namespace std;
within global space bad practice- you don't have declare variables @ beginning of function, necessary in old ansi c (about 20 years ago)
here's example how instead:
#include <iostream> #include <string> #include <vector> int main() { std::string day, date; int registercount; std::cout << "input data" << std::endl << std::endl << "enter day in want perform register: " << std::endl; std::cin >> day; std::cout << "date:" << std::endl; std::cin >> date; std::cout << "enter number of registers wanna perfom day " << day << ":" << std::endl; std::cin >> registercount; std::vector<std::string> registers(registercount); (int = 0; < registercount; ++i) { std::cout << "register " << << ":" << std::endl; std::getline(std::cin, registers[i]); } std::cout << "the data day of " << day << " following: " << std::endl; std::cout << "date: " << date << std::endl; (int = 0; < registercount; ++i) std::cout << registers[i] << std::endl; }
note might wrap std::getline(std::cin, registers[i])
if
statement , check whether valid stream object has been return , in case of empty lines, read empty string might make sure !registers[i].empty()
.
Comments
Post a Comment