为什么我不能使用此scanf函数读取输入字符串?

时间:2014-10-24 15:32:43

标签: c++ scanf

输入:3只大象

输出:Ele

但是没有读取输入字符串..有什么帮助吗?

提前致谢

#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;
}

1 个答案:

答案 0 :(得分:3)

scanf - 是一个C函数。它对C ++类std::string一无所知。其格式说明符%s用于在字符数组中输入数据。

你混合了两种语言:C和C ++。这是一种糟糕的编程风格。而不是循环

while ( scanf ("%d %s",&n, input ) != EOF ) 
{

        string sub = input.substr(0,n);
        cout<< sub;
}

使用以下循环

while ( std::cin >> n >> input ) 
{

        string sub = input.substr(0,n);
        cout<< sub;
}
相关问题