Input: 3 Elephant
Output: Ele
but the input string is not read.. any help?
Thanks in advance
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int n;
string input;
while ( scanf ("%d %s",&n, input ) != EOF )
{
string sub = input.substr(0,n);
cout<< sub;
}
getchar();
return 0;
}
scanf
- is a C function. It knows nothing about C++ class std::string
. Its format specifier %s
is used to enter data in a character array.
You mixed two languages: C and C++. It is a bad style of programming. Instead of the loop
while ( scanf ("%d %s",&n, input ) != EOF )
{
string sub = input.substr(0,n);
cout<< sub;
}
use the following loop
while ( std::cin >> n >> input )
{
string sub = input.substr(0,n);
cout<< sub;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments