gpt4 book ai didi

c++ - 涉及字符串输入和字符串比较的scanf问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:55:17 24 4
gpt4 key购买 nike

我最近才开始研究一般的 scanf 和 printf,在我的研究和一般的搞砸中,我多次在我的代码中遇到这个问题,所以我决定制作一个测试程序并成功地复制了错误。

#include <string>
#include <string.h>
#include <stdio.h>

int main(){
std::string name;
std::string name2;

printf("Print donald or larry: ");
scanf("%s",name);

if(strcmp(name.c_str(), "donald") == 1){
printf("You entered donald");
goto stop;


}else{
printf("You entered larry");
goto stop;
}



stop:
return 0;
}

当我尝试编译代码时,它从第 10 行抛出一个错误

错误:

error: cannot pass objects of non-trivially-copyable type 'std::string {aka
class std::basic_string<char>}' through '...'|

来源:

scanf("%s", name);

我都试过了name.c_str&name而且它们都不起作用,name.c_str使 if 语句出现错误并且无法正常工作,但 &name完全崩溃了,尽管我发现&<variable>目前仅适用于整数。

我做错了什么?

最佳答案

如果您正在尝试编写 C++ 代码,请使用以下代码

#include <iostream>
using std::cout;
using std::endl;
using std::cin;
#include <string>
using std::string;

int main(){

// declare the string object
std::string name;

// output prompt and get input
cout << "Print donald or larry: ";
cin >> name;

if (name == "donald") {
cout << "You entered donald" << endl;
}
else if (name == "larry") {
cout << "You entered larry" << endl;
}

return 0;
}

你在上面的代码中做了一些“错误”的事情。

  1. scanf 和 printf 是 C 函数,应该与 cstrings 一起使用而不是 string对象。如果您使用 std::string , 那么你正在用 C++ 编程,你应该使用 C++ 标准库头文件提供的功能 <iostream>
  2. 使用 goto在你的代码中通常是个坏主意。

关于c++ - 涉及字符串输入和字符串比较的scanf问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35237990/

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