-4

我想将一个整数和一个字符串存储在一个名为 X 的变量中,然后显示它。

int X;
printf("enter a number or a name")
scanf("%d", &X);
printf("%d", X);

显然我需要用 String 类型和 int 类型声明变量 X,我该如何在 C 中做到这一点?谢谢

4

4 回答 4

8

你不能那样做。诚然,您可以将两种类型存储在同一个变量中——查看 a 的union作用——但不能将其中一种类型提供给scanf()扫描字符串数字。

声明X为字符串,scanf()对于一个字符串,然后用strtol()来尝试从字符串中读取一个数字。如果strtol()返回零 errno设置(最后一个很重要,因为strtol()如果用户键入也会返回零0),那么转换失败并且没有数字,所以你有一个名字。

于 2012-04-17T05:24:27.837 回答
7

In a comment, you've (finally) indicated what you're trying to accomplish:

I prompt the user to enter a number or the word exit to exit the program.

You've assumed, incorrectly, that storing either a string or an integer into the same variable is the way do to this. It isn't.

Here's a general outline:

  1. Read a line of input into a string. Use fgets() for this.

  2. Check whether the line of input is the string "exit". Remember that fgets() leaves the newline ('\n') character in the string; you'll have to allow for that. To compare string values, use strcmp(). If the input string matches "exit", exit the program.

  3. If the string wasn't "exit", check whether it's an integer -- more precisely, whether it's a sequence of characters representing an integer. You can use strtol() for this. For example, if the input string is "123", then strtol() will return the long value 123. strtol() can also tell you if the integer value represented by the string is out of range, or whether it represents an integer value at all. Decide what you want to do if the input is "foobar", or "-123", or "".

You're going to want to carefully read the documentation for all these functions.

The key point is that you'll need two variables, an array of char to hold the input line, and an integer (int or long) to hold the converted integer value if the string holds the representation of an integer.

(I'm not providing code because, frankly, this smells like homework.)

于 2012-04-17T07:49:09.347 回答
0
struct StringAndInt
{
    int theInt;
    char *theString; /* or whatever type you want */
};

struct StringAndInt X;

C++ 有更好的选择。

于 2012-04-17T05:19:53.837 回答
0

你真的不能那样做。但是您可以将输入读取为字符串并将其转换为 int

char input[25];
int value = 0;

fgets(input, 25, stdin);
value = atoi(input);

printf("String Value = %s and Int Value = %d", input, value);
于 2012-04-17T05:32:47.850 回答