gpt4 book ai didi

c++ - 打印出存储在 vector 中的字符串

转载 作者:行者123 更新时间:2023-11-28 05:45:00 24 4
gpt4 key购买 nike

这是一个基本问题,但我是 C++ 的新手,所以提前致歉:)

我似乎无法打印出存储在 vector 中的字符串。我使用过 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]); 

最佳答案

你不应该使用 scanf 来读取 std::string,因为 %s modified 接受 char*。您也不应该使用 printf("%s", &names[i]); 来打印 std::string 对象。

scanfprintf 是 C 函数。 C 语言中没有 std::string 类型,因此,它们使用普通的 char 数组进行操作。

您应该使用 std::cinstd::cout 而不是 scanfprintf:

std::string str;
std::cin >> str; // input str
std::cout << str; // output str

关于c++ - 打印出存储在 vector 中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36405202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com