Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a string with scanf() in C++?

I can read a string with std::cin but I don't know how to read with one withscanf(). How can I change the code below to use scanf() ?

string s[20][5];

for (int i=1;i<=10;i++)
{
  for (int j=1;j<=3;j++) 
  {
      cin>>s[i][j];
  }
}
like image 821
Elmi Ahmadov Avatar asked May 06 '11 11:05

Elmi Ahmadov


People also ask

Can you use scanf for Strings in C?

You can use the scanf() function to read a string. The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).

Why scanf Cannot be used to read a string?

scanf by default stops at whitespaces that are not included in the format string. In your case it will read all characters until the first whitespace character into expr, so if your input is a sentence in english, it will grab the first word. If you're looking to grab a whole line, check out the fgets function.

What is scanf format string?

A scanf format string (scan formatted) is a control parameter used in various functions to specify the layout of an input string. The functions can then divide the string and translate into values of appropriate data types. String scanning functions are often supplied in standard libraries.

How do you read and write strings in C?

C provides two basic ways to read and write strings. input/output functions, scanf/fscanf and printf/fprintf. Second, we can use a special set of string-only functions, get string (gets/fgets) and put string ( puts/fputs ).


2 Answers

Using the C scanf() function requires using C strings. This example uses a temporary C string tmp, then copies the data into the destination std::string.

char tmp[101];
scanf("%100s", tmp);
s[i][j] = tmp;
like image 200
Greg Hewgill Avatar answered Oct 20 '22 15:10

Greg Hewgill


You can't, at least not directly. The scanf() function is a C function, it does not know about std::string (or classes) unless you include .

like image 39
unwind Avatar answered Oct 20 '22 16:10

unwind