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];
}
}
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.).
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.
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.
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 ).
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;
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 .
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