C++ 字符串变量声明

标签 c++ string variables declaration

我在声明字符串变量时遇到了一些问题。代码和错误在这里:http://pastebin.com/TEQCxpZd对我做错了什么有什么想法吗?另外,请保持平台独立。谢谢!

#include <stdio.h>
#include <string>
using namespace std;

int main()
{
    string input; //Declare variable holding a string

    input = scanf; //Get input and assign it to variable
    printf(input); //Print text
    return 0;
}


Getting this from GCC:

main.cpp: In function ‘int main()’:
main.cpp:53:10: error: invalid conversion from ‘int (*)(const char*, ...)’ to ‘char’
main.cpp:53:10: error:   initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::operator=(_CharT) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>]’
main.cpp:54:14: error: cannot convert ‘std::string’ to ‘const char*’ for argument ‘1’ to ‘int printf(const char*, ...)’

最佳答案

您正在混合使用 C++ 和 C I/O。在 C++ 中,这是,

#include <string>
#include <iostream>

int main(void)
{
   std::string input;
   std::cin >> input;
   std::cout << input;
   return 0;
 }

关于C++ 字符串变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4743564/

相关文章:

c++ - 如何改进基于sse的矩阵乘法

c++ - 我必须使用 0.f 初始化 float 吗?

python - 传递变量以供模块导入和使用

php - 附加变量到php数组输出中?

c++ - C++ 中是否可以使用三元运算符在 if 语句中选择比较运算符?

c++ - 在 C++ 中用字符串填充数组

python - 有没有办法撤消递归正则表达式操作?

c++ - 将调用推送到 STL 队列 <std::string> 会在从套接字读取字符串时导致段错误

c++ - 在给定数组中找到所有唯一的三元组,总和为零,执行时间最短

c - 使用C替换文件中的字符串