简体   繁体   中英

For loop to input strings in vector using getline

So I have an assignment for school, I need to declare a vector of strings then use a for loop to input names into the vector using get line. This code is what I have so far, I was trying to make a variable for a location in my vector, then input a string into the vector based on the value of my variable. Im using C++.

What Im wondering is: whats the flaw in my logic?

#include "stdafx.h"
#include <iostream>;
#include <vector>;
#include <string>;
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
vector<string> name_list(10);
int n;
for (name_list[n]; cin.getline >> name_list[n]; ++n)
    cin >> name_list[n];
cout << name_list[n];
int stop; cin >> stop;
return 0;
}

EDIT::: So I figured it out! Thank you 0x499602D2, You kinda set me on the right way. the code I came up with is this::

int _tmain(int argc, _TCHAR* argv[])
{
vector<string> name_list(11);
int n = 0;
for (int n = 0; n < 11; ++n);
getline(cin, name_list[n]);
cout << name_list[n];

int stop; cin >> stop;
return 0;
}

Not only is n uninitialized, you're also doing cin.getline >> name_list[n] which shouldn't even compile as far as I know. getline is a member function of std::cin that reads a line from input into a character array. It's not needed here as we are trying to read into a vector.

Moreover, since you want to get names from the user input into each slot in the vector, attempting to retrieve a line with getline also wouldn't make sense.

n needs to be initialized to an integer that when access with name_list[n] , will give us the start of the vector (that would be 0 ), and instead of getline , we use the operator >> to get each whitespace separated input. Like this:

for (int n = 0; std::cin >> name_list[n]; ++n)
    ; // empty

A statement isn't needed within the for loop body as its already been done in the loop parameters.


Another thing you need to look out for is overrunning the size of the vector. You initialized name_list with a size of 10 , and if the user enters in, say, 11 names, accessing an index with name_list[n] will cause Undefined Behavior in your program, which is a special way of saying your program will be invalid.

It's better to use the at() member function as it will throw an exception if you try to access an out-of-bounds address:

for (int n = 0; std::cin >> name_list.at(n); ++n)
//                                   ^^^^^^
    ;

您需要初始化n = 0,在第二个for参数中,您可能想将cin移入循环并用i <10替换它,因为否则循环将不知道何时停止

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM