There is such code:

char tmpBuff[255]; fgets(tmpBuff, 255, stdin); NSString *tmpStr = [[NSString alloc] initWithBytes:tmpBuff length:255 encoding:NSASCIIStringEncoding]; 

But the problem is that garbage is also copied to the string. I enter "Hello World!". Tried to process with the help stringByTrimmingCharactersInSet but did not help. Tell me how to correctly read the input from the console to the string.

  • My code works great for me by the way. - VioLet


2 answers 2

  char* ch = new char [255]; gets(ch); l = strlen(ch); 

    There is an operator like scanf():

     char tmpBuff[255]; // выражение в квадратных скобках указывает на то, // что нужно считывать всю строку с пробелами scanf("%[^\n]s",tmpBuff); NSString *tmpStr = [[NSString alloc] initWithBytes: tmpBuff length: sizeof(tmpBuff) encoding: NSASCIIStringEncoding]; NSLog(@"%@",tmpStr); 

    UPD.

     int newLength = 0; for (int i = 0; i < 256; i++) { if (tmpBuff[i] != ' ') { newLength++;} else break; 
    • but this did not solve the problem, [tmpStr length] is still equal to 255. And I need to know the actual size of the string, i.e. before \ n - ArtFeel
    • So you did not ask about this kind of like. See UPD. - VioLet pm
    • I agree, I did not quite correctly formulate the question, I did the trim, but it didn’t work, everything turned out to be much easier. - ArtFeel