this is a basic question but I'm new to C++ so apologies in advance :)
I couldn't seem to print out the strings I stored in a vector. I have used std:: cout as well as printf but printf seems to give the error "The program has stopped working". Where am I going wrong?
Here's the code with std::cout :-
#include <iostream>
#include <cstdio>
#include <vector>
#include <fstream>
using namespace std;
int main(){
int np;
string temp;
scanf("%d", &np);
vector <int> money;
vector <string> names;
for(int i = 0; i< np; i++){
scanf("%s", &temp);
names.push_back(temp);
cout << names[i] << endl;
}
return 0;
}
This didn't return any string at all.
The other program I tried with printf is exactly the same, except the cout line is replaced with:
printf("%s", &names[i]);
You can't use scanf()
to read integers right away.
This should work:
int np;
std::string temp;
std::cout << "Enter the size: ";
std::cin >> np;
//vector <int> money;
std::vector<std::string> names;
for (int i = 0; i< np; i++) {
std::cin >> temp;
names.push_back(temp);
std::cout << names[i] << endl;
}
You should not use scanf
for reading a std::string
, because %s
modified accepts a char*
. You also shouldn't use printf("%s", &names[i]);
for printing a std::string
object.
scanf
and printf
are C functions. There is no std::string
type in the C language, so, they are operating with plain char arrays.
Instead of scanf
and printf
you should use std::cin
and std::cout
:
std::string str;
std::cin >> str; // input str
std::cout << str; // output str
There are two things you need to change about your code. First, of all, scanf() doesn't support any c++ classes. You can read more about it on this link . Second , to replace scanf(), you can use getline(cin, temp) . In order to use it, you should add a line cin.ignore(); before a getline call is made because you you enter a number and press enter a '\\n' character gets inserted in the cin buffer that will be use the next time you call getline.
#include <iostream>
#include <cstdio>
#include <vector>
#include <fstream>
using namespace std;
int main(){
int np;
string temp;
scanf("%d", &np);
vector <int> money;
vector <string> names;
cin.ignore();
for(int i = 0; i< np; i++){
getline(cin, temp);
names.push_back(temp);
cout << names[i] << endl;
}
return 0;
}
Look at the working demo of the code here .
I hope I was able to explain it properly.
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.