-1

Say I have:

....
char aLine;
char inputLine[1000];
scanf("%c", &aLine);
....

Now, I want to convert aLine into an array of char so that I can count how many characters in aLine. How can i do this?

kluo
  • 131
  • 1
  • 10
  • Why transfer? `scanf("%c", aLine);` . or `scanf("%c", aLine+i);` is populating in a loop. Pretty expensive way to read a character sequence, but whatever. And fyi, if all you're doing is counting characters, you generally don't need an array at all. just count them as you see them in a `fgetc` loop. – WhozCraig Sep 18 '18 at 20:47
  • What does "count how many characters in aLine" mean? There's exactly 1. – interjay Sep 18 '18 at 20:50
  • OP asked a [similar question](https://stackoverflow.com/questions/52392825/c-how-to-use-while-feof-loop-to-solve-empty-input-file-problem) not long ago. – Weather Vane Sep 18 '18 at 21:16

1 Answers1

1

Statement scanf("%c",... reads in a single character, so there is actually no need to count it. If you want to "convert" a single character into a string (for which you could then apply, for example, strlen()), write the character at a particular position. Don't forget to terminate the string with \0 (or 0x0) such that string functions like printf("%s"... or strlen() work correctly:

char aLine;
char inputLine[1000];
scanf("%c", &aLine);
inputLine[0] = aLine;
inputLine[1] = '\0';

printf("inputLine: '%s' has length %d", inputLine, strlen(inputLine));

or simply read in a complete line at once:

char inputLine[1000];
if (fgets(inputLine,1000,stdin)) {
   printf("inputLine: '%s' has length %d", inputLine, strlen(inputLine));
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58