2012-3

/*
2020/4/20
第二次编写
*/
#include <iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using namespace std;

const int MAXWORD = 20;
char str[320];

struct node
{
    char word[MAXWORD];
    int index;
}words[320];

//考场中发现这种方法错误,但是不知道哪里出错,那就换一种方法重写
void preProcess()
{
    int len = strlen(str);
    for(int i = 0;i<len;i++)
    {
        if(str[i] == '"')
        {
            while(str[++i] != '"')
            {
                str[i] = '#';
            }
        }
    }
}

char getWord(char word[],int lim,char str[],int &i)//char getWord(char word[],int lim,char str[],int &i)
{
    char *w = word;
    while(isspace(str[i]))
    {
        i++;
    }

    if(str[i]!=EOF)
        *w++ = str[i];

    if(!isalpha(str[i]))
    {
        *w = '\0';
        return str[i];
    }

    i++;
    for( ;--lim;w++)
    {
        if( isalnum(str[i]) || str[i] == '_' )
        {
            *w = str[i];
            i++;
        }
        else
        {
            break;
        }
    }

    i--;
    *w = '\0';
    //***********************************************printf("Hello%s\n",w);在这里肯定不能够输出啊指针w指向字符串的末尾
    return w[0];
}

int main()
{

    gets(str);
    preProcess();

    char c;
    char word[MAXWORD];
    int index = 0;
    int count_word = 0;
    int temp = index;
    while( c = getWord(word,MAXWORD,str,index) != EOF )//*********while( (c = getWord(word,MAXWORD,str,index)) != '\0' )   不能使用字符‘\0'当做返回值,未知的错误
    {
        if(isalpha(word[0])) //**********************************if( isalpha(c) )这种写法错误
        {
            strcpy(words[count_word].word,word);
            words[count_word].index = temp;
            count_word++;
        }
        index++;
        temp = index;
        if(index>=strlen(str)) break;//***************碰到字符串可以在循环外部通过字符串的长度退出循环(循环条件EOF没关系)
    }

    for(int i = 0;i<count_word;i++)
    {
        if(strcmp(words[i].word,"if") == 0  || strcmp(words[i].word,"while") == 0 ||strcmp(words[i].word,"for") == 0)
        {
            printf("%s:%d\n",words[i].word,words[i].index);
        }
    }

    return 0;
}
/*
IN:
#include<stdio.h> int main(){int ifwhile=0; int forif=1; char if_for_while='a';char *str="while";while(ifwhile==0){ifwhile=1;forif=0;}if(forif==0){if_for_while='b';}if(ifwhile==1){if_for_while='c';}return 0;}
OUT:
while:97
if:134
if:165
*/
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值