c++ - I am trying to fill vector array with getline, what's wrong? -
i fill vector array lines don't same back. problem code?
using namespace std; vector<string> calling(int n){ vector<string> file(n); int a=0; while(n){ getline(cin,file[a]); cin.ignore(); a++; n--; } return file; } int main() { int n; cin >> n; vector<string> hrml = calling(n); int a=0; while(n){ cout << hrml[a] <<endl; a++; n--; } return 0; }
the input:
3 aaaa aaa aa bb b bbbb c cc ccc
the output:
aaaa aaa aa bb b bbbb
it's combination of few factors.
reading first number in input, 3
, doesn't move "cursor" next line; moves past number. when next call getline
, returns std::string
of size 0, because grabs space between end of character , end of line, nothing.
then, because you're using number explicit number of strings read, you're reading 3 lines: ""
, "aaaa aaa aa"
, , "bb b bbbb"
.
hence output missing line of 'c'
's.
the simplest solution here force call getline
before call calling
. (i've removed using namespace std;
code because it's bad practice)
int main() { int n; std::cin >> n; std::string line; std::getline(std::cin, line);
then, can rewrite calling
not need integer parameter:
std::vector<std::string> calling(){ std::vector<std::string> file; std::string line; while(std::getline(std::cin, line)){ file.push_back(std::move(line)); } return file; }
(if you're testing in console, , need mark end of line, use ctrl+z on windows or ctrl+d on unix.)
which changes calling line this:
std::vector<std::string> hrml = calling();
or this, if you're using c++11 (and don't mind loss of explicitly visible type declaration):
auto hrml = calling();
and long we're here, can write better loop printing contents of our vector:
for(size_t = 0; < hrml.size(); i++) { std::cout << hrml[i] << std::endl; }
or, if we're using c++11:
for(std::string const& line : hrml) { std::cout << line << std::endl; }
and, if you're allowed change format of input file, can ditch reading of number in first place, yielding smaller , easier debug program:
#include<iostream> #include<string> #include<vector> std::vector<std::string> calling(){ std::vector<std::string> file; std::string line; while(std::getline(std::cin, line)) { file.push_back(std::move(line)); } return file; } int main() { std::vector<std::string> hrml = calling(); for(std::string const& line : hrml) { std::cout << line << std::endl; } return 0; }
Comments
Post a Comment