I'm having some trouble declaring a string variable. Code and the errors are here: http://pastebin.com/TEQCxpZd Any thoughts on what I'm doing wrong? Also, please keep it platform independent. Thanks!
#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*, ...)’
Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string. char str_name[size]; In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store.
To declare variables in JavaScript, you need to use the var, let, or const keyword. Whether it is a string or a number, use the var, let, or const keyword for its declaration. But for declaring a string variable we had to put the string inside double quotes or single quotes.
The general syntax of declaring a string in C is as follows: char variable[array_size]; Thus, the classic declaration can be made as follows: char str[5]; char str2[50]; It is vital to note that we should always account for an extra space used by the null character(\0).
Data types in C C has a few built-in data types. They are int , short , long , float , double , long double and char . As you see, there is no built-in string or str (short for string) data type.
You are mixing c++ and c I/O. In C++ this is,
#include <string>
#include <iostream>
int main(void)
{
std::string input;
std::cin >> input;
std::cout << input;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With