C:要求用户输入字符串。编写一个将字符串作为参数的函数,如上所述对消息进行加密并返回密文

时间:2018-11-05 22:04:24

标签: c

我目前正在从事一项作业,我以为自己已经完成了,但是我的while循环处于一个恒定的无限循环中,我不知道自己在哪里搞砸。我曾尝试获得帮助,但TA并没有太大帮助。如果您可以看一下,将不胜感激。 。 。 。 。 。 。 。 。 。 。 。 。 。 。 。

class FlatFileParse
{
    public static void Parse()
    {
        var engine = new FixedFileEngine<Customer>();
        Customer[] result = engine.ReadFile("wrapped.dat");

        foreach (var detail in result)
            Console.WriteLine(" Client: {0},  Name: {1}", detail.DateScheduled, detail.PatientName);
    }
}

[FixedLengthRecord()]
public class Customer
{
    [FieldFixedLength(5)]
    public int InitialNull;

    [FieldFixedLength(7)]
    public string Date1;

    [FieldFixedLength(1)]
    public int OfficeId;

    [FieldFixedLength(3)]
    public int CustomerId;

    [FieldFixedLength(15)]
    public int CustomerName;

}

1 个答案:

答案 0 :(得分:0)

如果您在getchar之后添加scanf("%c", &choice);,您的问题将得到解决。

您遇到的问题是由输入流中留下的换行符引起的。输入y并按Enter键(假设没有其他操作)后,在输入流中保留换行符;在下一次迭代中调用gets时,将plain_text设置为“ \ n”时将使用换行符。

当您输入多个字符时,会出现这种情况:

$ ./main.exe
Please enter a message: hello
The encrypted message is: elhlo
Do you want to continue (Y/N)? : yes please
Please enter a message: The encrypted message is: spese lae
Do you want to continue (Y/N)? :

要解决上述问题,请添加另一个循环以在第一个字符之后使用所有字符,直到找到换行符为止:

scanf("%c", &choice);
while(getchar() != '\n')
    continue;

现在观察结果:

$ gcc main.c -o main.exe; ./main.exe;
Please enter a message: hello
The encrypted message is: elhlo
Do you want to continue (Y/N)? : yes please
Please enter a message:

注意

gets不应使用。请改用fgets,因为它可以防止缓冲区溢出。