PAT B1009 error: ‘gets’ was not declared in this scope gets(s)之解决办法

1009 说反话 (20 分)

给定一句英语,要求你编写程序,将句中所有单词的顺序颠倒输出。

输入格式:

测试输入包含一个测试用例,在一行内给出总长度不超过 80 的字符串。字符串由若干单词和若干空格组成,其中单词是由英文字母(大小写有区分)组成的字符串,单词之间用 1 个空格分开,输入保证句子末尾没有多余的空格。

输出格式:

每个测试用例的输出占一行,输出倒序后的句子。

输入样例:

Hello World Here I Come

输出样例:

Come I Here World Hello

初次代码:

#include <stdio.h>
#include <string.h>

int main(){
    char s[90];
    gets(s);
    int len=strlen(s);
    int last=len;
    bool first=true;
    for(int i=len-1;i>=-1;i--){
        if(i==-1 || s[i]==' '){
            if(first)
                first=false;
            else
                printf(" ");
            for(int j=i+1;j<last;j++)
                printf("%c",s[j]);
            last=i;
        }
    }
}

       结果是编译错误: error: ‘gets’ was not declared in this scope gets(s)。这个错误是始料未及的,毕竟在codeblock中是可以顺利编译的,最多是结果有错,而且get(str)的操作在算法笔记是有详细说明可使用的,搜索后发现get()方法确实已经不被PAT编译器支持,并且网上也有一些方法改进对一行字符串输入的读取。我这里采用的是cin.getline的操作。

改变之处在于:

①增加#include<iostream>

           using namespace std;

②gets  --> cin.getline

代码如下:

#include <stdio.h>
#include <string.h>
#include<iostream>

using namespace std;

int main(){
    char s[90];
    cin.getline(s,90);
    int len=strlen(s);
    int last=len;
    bool first=true;
    for(int i=len-1;i>=-1;i--){
        if(i==-1 || s[i]==' '){
            if(first)
                first=false;
            else
                printf(" ");
            for(int j=i+1;j<last;j++)
                printf("%c",s[j]);
            last=i;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36525099/article/details/86631881