【发布时间】:2016-04-04 14:18:19
【问题描述】:
这是一个基本问题,但我是 C++ 新手,所以提前道歉 :)
我似乎无法打印出存储在向量中的字符串。我使用了 std:: cout 和 printf 但 printf 似乎给出了错误“程序已停止工作”。我哪里错了?
这是带有 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;
}
这根本没有返回任何字符串。
我用 printf 试过的另一个程序是完全一样的,只是 cout 行被替换为:
printf("%s", &names[i]);
【问题讨论】:
-
使用 cin
-
我认为你需要一本好的初学者书籍,here's a list of a few。
-
如果
scanf("%s", &temp);没有当着你的面抛出编译器警告,你需要将你的警告级别提高到更迂腐的程度。
标签: c++ string vector stl printf