从行读单词

时间:2014-11-09 09:03:25

标签: c string pointers

我不知道问题出在哪里。第一个函数readline工作完美,但第二个功能不起作用。错误:赋值使得整数指针没有强制转换。

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

#define MAX_LINE 1024

char line[MAX_LINE];
int line_length = 0;
int pocet_radek=0;
int input;
char cell;


char* readline(char* line){
line[line_length] = 0;
while ( (input = getchar()) != '\n' && line_length < MAX_LINE - 1) {
  line[line_length] = input;
  line_length++;
  }
  pocet_radek++;
  printf("%d\n", pocet_radek);
  return line;
}

char* read_cell(char* line, char* cell){
int i;
for(i=0;i<line_length;i++){
if( line[i]!=' ' || line[i]!='\n')
cell=line[i];
}
return cell;
}

int main()
{
printf("%s",readline(line));
printf("%s",read_cell(line, cell));
return 0;
}

2 个答案:

答案 0 :(得分:0)

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

#define MAX_LINE 1024

char line[MAX_LINE];
int line_length = 0;
int pocet_radek=0;
int input;
char *cell; //global variables can be used in any function


char* readline(){ //No need for any parameters
   line[line_length] = 0;
   while ( (input = getchar()) != '\n' && line_length < MAX_LINE - 1) {
      line[line_length] = input;
      line_length++;
   }
   pocet_radek++; //This variable doesn't make sense as
   printf("%d\n", pocet_radek); //This will always print 1
   return line;
}

void read_cell(){
   if((cell=strtok(line," "))==NULL)
      return(-1);
   do
     printf("\"%s\"\n",cell);
   while((cell=strtok(NULL," "))!=NULL);
}

int main()
{ 
  printf("%s\n",readline());
  read_cell();
  return 0;
 }

答案 1 :(得分:0)

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

#define MAX_LINE 1024

int pocet_radek=0;

char *readline(char* line, size_t size){
    int input, line_length = 0;

    while ((input = getchar()) != EOF && input != '\n' && line_length < size - 1) {
        line[line_length++] = input;
    }
    line[line_length] = 0;
    if(!line_length && input == EOF)
        return NULL;
    pocet_radek++;
    printf("%d\n", pocet_radek);
    return line;
}

char *read_cell(char **pos){
    char *ret = *pos;
    if(!ret)
        return NULL;
    while(isspace(*ret))
        ++ret;
    if(!*ret)
        return NULL;
    *pos = ret;
    while(**pos && !isspace(**pos))
        ++*pos;
    if(**pos == 0)
        *pos = NULL;
    else {
        **pos = 0;
        ++*pos;
    }
    return ret;
}

int main(void){
    char line[MAX_LINE];
    char *p, *cell;

    while(readline(line, sizeof line)){
        printf("line:%s\n", line);
        p = line;
        while(cell = read_cell(&p))
            printf("word:'%s'\n", cell);
    }
    return 0;
}