繁体   English   中英

如何在 c 中使用 for 循环在一行中打印全文?

[英]how to print full text in one line using for loop in c?

我正在使用 for 循环为字符串中的每个字符添加一个并将它们打印出来,但是在打印它们时,每个字母都在新行上形成,顺便说一下,我是 C 语言的初学者。 任何慷慨的帮助将不胜感激。 顺便说一句,我知道它们是因为 for 循环的工作原理而打印的每个字母,但我不知道如何修复它

for (int i = 0; i < strlen(text); i++)
{
    char c = plaintext[i];
    printf("CipherText: %c\n", c + 1);
}

这是 output:

Plaintext: hello
CipherText: i
CipherText: f
CipherText: m
CipherText: m
CipherText: p
printf("CipherText: );
for (int i = 0; i < strlen(text); i++)
{
char c = plaintext[i];
printf(" %c", c + 1);
}

只需删除\n (换行符)字符。
(以及其他一些建议。)

int main(void)
{
    char plaintext[] = "this is original cipher";
    char c = 0;//create this before entering loop
    size_t len = strlen(plaintext);//assign length to variable that can be used in for statement
    printf("%s", "CipherText: ");//print this before entering loop
    for (int i = 0; i < len; i++)
    {
         c = plaintext[i];//output each char in sequence
         printf("%c", c + 1);//output each char in sequence
    }
    printf("%s", "\n");//Optional = moves the cursor to the next line in case
                       //there are follow-on lines to printf
    getchar();
    return 0;
}

对于给定的“纯文本”示例,这里是 output:
在此处输入图像描述

在这里,您有一个较短的版本:

printf("Ciphertext:");
for (const char *i = plaintext; *i; i++)  printf("%c", *i + 1);

或没有指针

printf("Ciphertext:");
for (size_t index = 0; plaintext[index]; index++)  printf("%c", plaintext[index] + 1);

而不是printf在循环中你可以使用putchar但大多数优化编译器会为你做

您也可以通过以下简短方式执行此操作:

#include <stdio.h>

int main(void) {
  char str[] = "hello";
  printf("PlainText: %s\nCipherText: ", str);

  for( int i = 0; str[i] != '\0'; i++)
    putchar(str[i] + 1);

  return 0;
}

Output:

PlainText: hello
CipherText: ifmmp

每个以\开头的字符都称为转义字符,当您打印密文时,每次都使用转义字符\n打印它,称为换行符 这就是为什么密文中的每个字符都打印在新行上的原因。 只需从printf("CipherText: %c\n", c + 1);中删除\n 你会得到你所期望的 output。

您还可以在此 Wikipedia 页面上了解有关转义字符的更多信息。

您必须从 for 循环中删除 \n (换行符)字符。 与 Python 不同,C 不会添加新行,除非您添加 \n。

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

int main(void)
{
    string plaintext = get_string("plaintext: ");  // asking user to enter a word             
    for (int i = 0, n = strlen(plaintext); n > i ; i++) // looping through each entered letter
    {        
            printf("%c" , plaintext[i] + 1);   // changing the letter by 1 place                     
    }
    printf("\n");
}

暂无
暂无

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

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