【问题标题】:I'm learning C and I've made a simple program. It doesn't work and I need a an answer我正在学习 C 并且我制作了一个简单的程序。它不起作用,我需要一个答案
【发布时间】:2021-03-16 10:50:00
【问题描述】:

我正在学习 C 并且我编写了一个简单的程序,但它不起作用。代码如下:

#include <stdio.h>
#include <windows.h>

int main(int argc, char* argv[]){
    system("title test");
    printf("Arguments: %i\n", argc);
    for (int i, int i <= %s, argv[i], i++){
        switch (%s, argv[i]){
        case 1:
            printf("First Argument: %s\n", argv)
        }
    }
    return 0;
}

我打算添加更多内容,但首先我需要找出问题所在。请用答案来回答这个问题。我可能暂时不会回复,因为我很快就要睡觉了。抱歉,如果我违反了任何规则,我是 Stack Overflow 的新手,我还没有阅读规则,如果有的话。

顺便说一下,这里是错误的事情:

| 7|error: expected identifier or '(' before 'int'|
| 7|error: expected expression before ',' token|
| 8|error: expected expression before '%' token|
|11|error: expected ';' before '}' token|
|  |=== Build failed: 4 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

【问题讨论】:

  • for (int i, int i &lt;= %s, argv[i], i++){ 你确定这不是拼写错误?另请阅读tour
  • printf() 和家族需要格式说明符,而不是每个变量表示。

标签: c windows error-handling stack codeblocks


【解决方案1】:

首先,switch的语法是这样的:

switch (expression)
​{
    case constant1:
    // statements
     break;

   case constant2:
    // statements
    break;
   .
   .
   .
   default:
     // default statements
} 

switch 语句是如何工作的?

表达式被计算一次,并与每个 case 标签的值进行比较。

如果匹配,则执行匹配标签后的相应语句。例如,如果表达式的值等于 constant2,则 case constant2: 之后的语句将被执行,直到遇到 break。 如果没有匹配,则执行默认语句。

如果我们不使用break,则执行匹配标签之后的所有语句。

顺便说一句,switch语句中的default子句是可选的。

第二:

for循环的语法是:

 for(int i=(First value of control);i<=(Final value of control);Increment of control variable)

例子:

 for(int i=0;i<=10;i++)

【讨论】:

    【解决方案2】:

    你的程序有几个错误:

    • %s 没有任何意义
    • for (int i, int i &lt;= %s, argv[i], i++) 是错误的,d 没有任何意义。
    • 您的case 中缺少break。在这里并没有什么坏处,但是一旦您添加更多cases,您就会遇到麻烦。
    • 您希望i &lt; argcargc 至少为 1,因为 argv[0] 是程序的名称。

    你可能想要这个:

    #include <stdio.h>
    #include <windows.h>
    
    int main(int argc, char* argv[]) {
      system("title test");
      printf("Arguments: %i\n", argc);
      for (int i = 0; i < argc; i++) {  // use i < argc
        switch (i) {
        case 1:
          printf("First Argument: %s\n", argv[i]);
          break;   // this was missing
        }
      }
      return 0;
    }
    

    BTW switch/case 应该替换为 if here:

      for (int i = 0; i < argc; i++) {
        if (i == 1) {
          printf("First Argument: %s\n", argv[i]);
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 1970-01-01
      • 2022-11-25
      • 1970-01-01
      • 2021-07-08
      相关资源
      最近更新 更多