FOR循环中的字符串

时间:2017-01-02 03:23:38

标签: c arrays string loops for-loop

我有一个问题。

我想要一个FOR循环,将文本打印出许多字符串。让我们说我输入我的姓氏和姓氏。并且FOR循环产生字符串。

#include <stdio.h>
int main(){

   char str1 [12];
   char str2 [12];
   char wordarray [2]={str1,str2}; // error here
   int i;

   printf ("Type your forname : ");
   scanf ("%s",&str1);
   printf ("\nType your last name : ");
   scanf ("%s",&str2);

   printf ("\n\nYour name is : ");
   printf ("%s\t%s",str1,str2);
   printf ("\n");

   for (i=0;i<3;i++){
      printf ("%s",wordarray [i]); // Error here . 
   } // end FOR

   return 0;
} // end MAIN

5 个答案:

答案 0 :(得分:2)

您需要使用scanf(或用于用户输入的任何函数)验证每次读取,以确保您拥有有效的数据。您还应该为读取提供宽度限制,以确保您不会超出阵列末尾。 (例如scanf ("%11s", str1))。您应该考虑使用fgets进行用户输入,并删除缓冲区中'\n'所包含的fgets。这将帮助您避免scanf通常困扰新用户的一些陷阱,尤其是在使用混合字符串和数字输入时。

除此之外,您还应该避免在代码中使用幻数(例如char str1[12])。如果您需要常量12,则需要define一个或声明enum来创建它。

将这些部分放在一起,你可以做类似的事情:

#include <stdio.h>

#define LEN 12

int main (void) {

    char str1 [LEN] = "";
    char str2 [LEN] = "";
    char *wordarray[] = {str1, str2};
    int i, nwords = sizeof wordarray/sizeof *wordarray;

    printf ("Type your forname   : ");
    if (scanf ("%11s", str1) != 1) {
        fprintf (stderr, "error: invalid input.\n");
        return 1;
    }
    printf ("Type your last name : ");
    if (scanf ("%11s", str2) != 1) {
        fprintf (stderr, "error: invalid input.\n");
        return 1;
    }

    printf ("\nYour name is : %s %s\n", str1, str2);

    for (i = 0; i < nwords; i++){
        printf ("%s", wordarray [i]);
    }
    putchar ('\n');

    return 0;
}

示例使用/输出

$ ./bin/name
Type your forname   : david
Type your last name : rankin

Your name is : david rankin
davidrankin

仔细看看,考虑其他答案,如果您有其他问题,请告诉我。另外,我还要考虑零输入或超过12个字符的输入。这将有助于在输入处理中建立稳健性。

如果您想使用fgets接近输入,可以使用以下内容改善输入处理:

#include <stdio.h>
#include <string.h>

#define LEN 12

int main (void) {

    char str1 [LEN] = "",
         str2 [LEN] = "",
         *wordarray[] = {str1, str2};
    size_t i, len = 0, nwords = sizeof wordarray/sizeof *wordarray;

    printf ("Type your forname   : ");
    if (!fgets (str1, LEN, stdin)) {    /* read with fgets/validate */
        fprintf (stderr, "error: invalid input.\n");
        return 1;
    }
    len = strlen (str1);                /* get length of str1     */
    if (str1[len-1] == '\n')            /* test for trailing '\n' */
        str1[--len] = 0;                /* overwrite with nulbyte */

    printf ("Type your last name : ");
    if (!fgets (str2, LEN, stdin)) {
        fprintf (stderr, "error: invalid input.\n");
        return 1;
    }
    len = strlen (str2);
    if (str2[len-1] == '\n')
        str2[--len] = 0;

    printf ("\nYour name is : %s %s\n", str1, str2);

    for (i = 0; i < nwords; i++){
        printf ("%s", wordarray [i]);
    }
    putchar ('\n');

    return 0;
}

答案 1 :(得分:0)

你不明白数组和指针是如何工作的。你应该阅读answer

#include <stdio.h>

int main(void) {
  printf("Type your forname : ");
  char str1[12];
  { // we open a scope because ret don't need to be in function scope
    int ret = scanf("%11s", str1); // scanf need to know how many bytes are
    // available without count `\0` and you must send the array itself not the
    // address
    if (ret != 1) {                        // scanf don't set str1
      fprintf(stderr, "Error in input\n"); // stderr is the error stream
      return 1;
    }
  }

  printf("\nType your last name : ");
  char str2[12];
  {
    int ret = scanf("%11s", str2);
    if (ret != 1) {
      fprintf(stderr, "Error in input\n");
      return 1;
    }
  }

  printf("\n\nYour name is : ");
  printf("%s\t%s", str1, str2);
  printf("\n");

  char *word[2] = {str1, str2}; // we need an array of pointer
  for (size_t i = 0; i < sizeof word / sizeof *word; i++) { // size of array
    printf("%s", word[i]);
  }

  return 0;
}

答案 2 :(得分:0)

舒尔我不知道一切如何运作。这就是为什么我问:)谢谢你的回复。我会调查。有了这些信息,我将尝试构建一个更大的FOR循环,因此我可以在2D数组中插入值。用户可以将值添加到2d数组,然后更改插槽中的信息文本或数字。

#include <stdio.h>
#define lenght 12                // corrected, define string format lenght

int main(){

char str1 [lenght];              // corrected, strings should have format lenght
char str2 [lenght];              // corrected, strings should have format lenght
char *wordarray [2]={str1,str2}; // corrected, add a * to wordarray[2]
int i;

printf ("Type your forname : ");
scanf ("%s",str1);               // corrected, skip the & in ("%s",&str1);
printf ("Type your last name : ");
scanf ("%s",str2);               // corrected, skip the & in ("%s",&str2);

printf ("\n\nYour name is : %s\t%s\n",str1,str2);

for (i=0;i<2;i++){               // corrected, i<2 must match the array elements
printf ("%s\t",wordarray [i]); 
} // end FOR

return 0;
} // end MAIN

答案 3 :(得分:0)

确定。又去了。 没有用过很多字符串。该程序在数组中包含字符串和数字,并以FOR循环打印。我还试图让数组中的不可用元素可供用户使用,因此他可以更改值。

我猜我的风格非常糟糕。但是...它是我得到的。 现在关于GETS(str1),从用户那里获取一个字符串。在程序中第一次使用时,它表现正常。但是第二次在程序中我必须使用GETS(“%s”,str1),所以它表现得很好。还有一个问题是从用户所区分的数组中添加特定数字。显示在for循环...

另一个问题是在JUMP之后清除控制台屏幕。所以文字不会泛滥屏幕。

评论:我同意David C. Rankin对用户数据的验证很重要。只容忍字符串请求的字符输入和整数请求的数字。如果“特殊字符”如斜线或点,也返回错误输入。我试图阅读原创的K&amp; R C书,他们谈到了这个问题,主题包括将所有字母转换成小案或大案。但我遇到了运行示例代码的麻烦,可能是C89 C11编译器问题,我不知道。

#include <stdio.h>
//#include <string.h> // GCC32-C . mingw . compile
#define lenght 20    // Orbit_L75.Apartment_9

int main(){

int i,j,k,select,select2,*ptr;
char str1 [lenght];              
char str2 [lenght];             
char *wordarray [2]={str1,str2}; // character array must have a * asterix  pointer . 
int numarray [2];

printf ("Type your forname : ");
gets (str1); // gets (wordarray[0]) // alternative syntax       
printf ("Type your last name : ");
gets (str2);            

printf ("Enter your telephone number : ");            
scanf ("%d",&numarray[0]);     // assign a value to numarray slot 0
//scanf ("%d",(numarray+0));  // alternative syntax

printf ("Enter your age : ");
scanf ("%d",&numarray[1]); // assign a value to numarray slot 1
printf ("\n\n");

jump1 : 
printf ("=========================\n");
for (i=1;i<5;i++)
{printf ("%d\t",i);}
printf ("\n");

for (j=0;j<2;j++)
{printf ("%s\t",wordarray[j]);}
//printf ("%s\t",*(wordarray+j));} //  alternative syntax
printf ("\n");

for (k=0;k<2;k++)
{printf ("%d\t",numarray[k]);}
printf ("Sum = %d\n",(numarray[0]+numarray[1]));     // add numarray slot 0 and slot 1.
//printf ("Sum = %d",*(numarray+0)+*(numarray+1));  // alternative syntax
printf ("=========================\n");

printf ("\n\nSelect\n1: Change Telephone \n2: Change Age \n3: Change First Name \n4: Change Last Name \n5: RAM location\n");
scanf ("%d",&select);

if (select == 1)
{printf ("New number : ");
scanf ("%d",&numarray[0]);
//scanf ("%d",(numarray+0));               // alternative syntax
printf ("\n");}

else if (select == 2)
{printf ("New age : ");
scanf ("%d",&numarray[1]);
printf ("\n");}

else if (select == 3)
{printf ("New First Name : ");
scanf ("%s",str1); //problems with the display using GETS on the second run.
printf ("\n");} 

else if (select == 4)
{printf ("New Last Name : ");
scanf ("%s",str2);
printf ("\n");}

else if (select == 5)
{ // select2
{printf ("\nRAM location of : \n\t1. Telephone number\n\t2. Age\n\t3. First Name.\n\t4. Last Name\n");}
scanf ("%d",&select2);

if (select2 == 1)
{ptr = &numarray[0];
printf ("\nTelephone number\nValue in Decimal\t: %d\nValue in Hexadecimal\t: %ph\nRAM location in decimal\t: %d\nRAM location in Hex\t: %ph\n\n\n",*ptr,*ptr,ptr,ptr);}

else if (select2 == 2)
{ptr = &numarray[1];
printf ("\nAge\nValue in Decimal\t: %d\nValue in Hexadecimal\t: %ph\nRAM location in decimal\t: %d\nRAM location in Hex\t: %ph\n\n\n",*ptr,*ptr,ptr,ptr);}

else if (select2 == 3)
{ptr = &wordarray[0];
printf ("\nFirst Name\nValue in Text\t: %s\nValue in Hexadecimal\t: %ph\nRAM location in decimal\t: %d\nRAM location in Hex\t: %ph\n\n\n",*ptr,*ptr,ptr,ptr);}

else if (select2 == 4)
{ptr = &wordarray[1];
printf ("\nLast Name\nValue in Text\t: %s\nValue in Hexadecimal\t: %ph\nRAM location in decimal\t: %d\nRAM location in Hex\t: %ph\n\n\n",*ptr,*ptr,ptr,ptr);}

else if (select2 <1 || select2 > 4)
{printf ("\nValue is out of range, Try again .\n\n");}
} // end IF select2

else if (select <1 || select > 5)
{printf ("\nValue is out of range, Try again .\n\n");}

goto jump1;

return 0;
} // end MAIN

答案 4 :(得分:-1)

str1和str2实际上是指针。

wordarray是一组字符。它应该是char的指针数组。

同样在你的scanf中你传递了str1和str2的地址,但你应该只传递str1和str2。