简体   繁体   English

如何从用户输入中提取字符串?

[英]How do I extract a string from user input?

milage = atoi(strtok(NULL, " "));
drive(&cars[carID-1], milage);

I have something like this for numbers, I want to use same thing for a name (character). 我对数字有这样的要求,我想对名称(字符)使用相同的内容。

I tried this: 我尝试了这个:

user = strtok(NULL, " ");
rent(&cars[carID-1], user);

but it did not work out. 但没有成功。

Can any one help? 可以帮忙吗?

Are you just trying to extract numbers / strings from within another string? 您是否只是想从另一个字符串中提取数字/字符串? If that is the case you should probably have a look at sscanf . 如果是这种情况,您可能应该看看sscanf It works just like scanf but reads froms a string instead of from the standard input. 它的工作原理与scanf但是它从字符串中读取而不是从标准输入中读取。

char name[100]; int mileage;
sscanf("username 42", "%s %d", name, &mileage);
//name now contains "username" and mileage now contains 42

char * is not a string type. char *不是字符串类型。 char * is a pointer to byte array. char *是字节数组的指针。 Byte array is the string type. 字节数组是字符串类型。

Strings can be copied with strdup(). 可以使用strdup()复制字符串。 Copied strings need to be freed with free(). 复制的字符串需要使用free()释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM