/*
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
*/
2012-3
最新推荐文章于 2022-07-24 14:54:45 发布