Ultra Frosty Posted October 2, 2004 Share Posted October 2, 2004 When I run this, it doesnt ever print anything after a space. Why not ? #include <stdio.h> int main(int argc, char *argv[]) { char text[80]; printf("Text: "); scanf("%s", &text); int i = 0; while(text[i] != '\0') { printf("\ntext[%d] = %c", i, text[i]); i++; } return 0; } Link to comment Share on other sites More sharing options...
0 loc[a]lhost Posted October 2, 2004 Share Posted October 2, 2004 i think the problems lies here: scanf("%s", &text); you should write: scanf("%s", text); when an array is passed as a parameter, the pointer to it is passed and not the array itself. in your code, you are passing a pointer to a pointer to the array. Link to comment Share on other sites More sharing options...
0 Ultra Frosty Posted October 2, 2004 Author Share Posted October 2, 2004 Doesnt help. Thanks anyways. Link to comment Share on other sites More sharing options...
0 kjordan2001 Posted October 2, 2004 Share Posted October 2, 2004 I'm just being picky here, but scanf is not the best way to read in text since if the user types more than 80 characters, you'll get a buffer overflow. You can either use fgets, or do dynamic memory allocation for your array. fgets(buff, sizeof(buff), stdin); OR int maxlength = 80; int length = 0; char *text = (char*)malloc(sizeof(char)*80); char temp; while ((temp = getch()) != EOF) { if (length == maxlength) { maxlength = maxlength*2; text = realloc(text,sizeof(char)*maxlength); } *(text+length) = temp; ++length; } Depending if you want to go past the defined length. Link to comment Share on other sites More sharing options...
0 Mouton Posted October 3, 2004 Share Posted October 3, 2004 MSDN: "To read strings not delimited by space characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The corresponding input field is read up to the first character that does not appear in the bracketed character set. If the first character in the set is a caret (^), the effect is reversed: The input field is read up to the first character that does appear in the rest of the character set." So you need to use something like: scanf("%[a-z0-9 ]", &text); if you want to use scanf(). Link to comment Share on other sites More sharing options...
Question
Ultra Frosty
When I run this, it doesnt ever print anything after a space. Why not ?
#include <stdio.h> int main(int argc, char *argv[]) { char text[80]; printf("Text: "); scanf("%s", &text); int i = 0; while(text[i] != '\0') { printf("\ntext[%d] = %c", i, text[i]); i++; } return 0; }Link to comment
Share on other sites
4 answers to this question
Recommended Posts