The program is not taking input from cin>>input_name; ??? |
Don’t write a lot of code before compiling or it becomes hard to find the bugs.
Let’s have a look at it:
if (val1 == '0')
Here you ask for the
character ‘0’, whose integer value in the ASCII table is 48.
So this condition will become true only when "val1" is 48.
If you input 0, you don’t exit the while loop - I think that’s why you think the following std::cin instruction doesn’t work. Instead it works, but you don’t reach it.
for (int i1; i1 < name.size(); ++i1)
"i1" is uninitialized here.
It means it could contain a value which is already higher than name.size(), and this loop could be skipped.
name.size() returns a std::vector<std::string>::size_type, which is unsigned. You shouldn’t compare it to an int.
Alternatives:
- declare "i1" as std::vector<std::string>::size_type;
- declare "i1" as std::size_t (is defined in many headers);
- declare "i1" as gsl::index (needs a C++ guideline support library implementation);
- use std::vector::ssize() instead of size() (if your compiler supports it).
1 2 3
|
int i2;
i2 = i1;
cout<<"("<<name[i1]<<", "<<number[i2]<<")"<<endl;
| |
You don’t need "i2":
cout << "(" << name[i1] << ", " << number[i1] << ")" << endl;
Once tidied up your code works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
#include <iostream>
#include <string>
#include <vector>
int main()
{
std::cout << "Enter the name with number assigned: ";
int val1;
std::string name1;
std::vector<int> number;
std::vector<std::string> name;
std::vector<std::string> name_and_number;
while (std::cin >> name1 >> val1)
{
name.push_back(name1);
number.push_back(val1);
if (name1 == "NoName")
{
if (val1 == '0') {
break;
}
}
}
std::cout << "names and numbers are:\n";
for (std::vector<std::string>::size_type i1 {}; i1 < name.size(); ++i1)
{
int i2;
i2 = i1;
std::cout << '(' << name[i1] << ", " << number[i2] << ")\n";
}
std::cout << "\nEnter the name to find the corresponding number: ";
std::string input_name;
std::cin >> input_name;
std::cout << "input_name is " << input_name << '\n';
}
| |
Example:
Enter the name with number assigned: one 1 two 2 three 3 NoName 48
names and numbers are:
(one, 1)
(two, 2)
(three, 3)
(NoName, 48)
Enter the name to find the corresponding number: two
input_name is two |
Anyway there’s plenty of room for improvements.