#include <stdio.h>
#include <string.h>
void main(void)
{
char in[15], rev[15];
printf("Enter a word (upto 15 letters): ");
gets(in);
for (int i = 0, j = 15; i < strlen(in); i , j--)
{
rev[i] = in[j];
}
puts(rev);
}
顯示沒有錯誤,只是不作業。我究竟做錯了什么?
編輯:沒有 strrev
uj5u.com熱心網友回復:
對于根據 C 標準的初學者,不帶引數的函式 main 應宣告為
int main( void )
該函式gets不安全且不受 C 標準支持。而是使用scanf或fgets。
該函式strlen是一個標準的 C 字串函式。所以根據要求你可能不會使用它。
您沒有反轉字串。您正試圖以相反的順序將一個字串復制到另一個字串中。
該程式可以如下所示
#include <stdio.h>
int main(void)
{
enum { N = 15 };
char in[N] = "", rev[N];
printf("Enter a word (upto %d letters): ", N - 1 );
scanf( " s", in );
size_t n = 0;
while ( in[n] ) n;
rev[n] = '\0';
for ( size_t i = 0; i < n; i )
{
rev[n - i - 1] = in[i];
}
puts( rev );
}
uj5u.com熱心網友回復:
編輯:getline不是標準 C,它只被 POSIX 系統識別。另一種解決方案是使用fgets適用于兩種作業系統的方法。我提供了兩個例子。
正如其他人已經指出的那樣,您犯了一些錯誤:
- 獲取用戶輸入時的不安全做法。
- 即使輸入字串的字符數較少,也始終從 15 開始。
我創建了一個使用超過 15 個字符的動態分配的小示例,并修復了上述問題。注釋內嵌到關鍵點。
示例:getline - POSIX
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[]) {
// Idea from https://stackoverflow.com/questions/7709452/how-to-read-string-from-keyboard-using-c
char *line = NULL; /* forces getline to allocate with malloc */
size_t len = 0; /* ignored when line = NULL */
ssize_t read;
read = getline(&line, &len, stdin);
if (read > 0)
{
printf ("\n String from user: %s\n", line);
}else
{
printf ("Nothing read.. \n");
return -1;
}
// Now we need the same amount of byte to hold the reversed string
char* rev_line = (char*)malloc(read);
// "read-1" because we start counting from 0.
for (int i = 0, j = read-1; i < read; i , j--)
{
rev_line[i] = line[j];
}
printf("%s\n",rev_line);
free (line); /* free memory allocated by getline */
free(rev_line);
return 0;
}
示例:fgets - C 標準
fgets不回傳讀取的字符數,因此必須將其鏈接起來strlen以決定為反轉字串分配多少字符。
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <string.h>
int main (int argc, char *argv[]) {
char line[LINE_MAX];
size_t len = 0; /* ignored when line = NULL */
ssize_t read;
if (fgets(line, LINE_MAX, stdin) != NULL)
{
line[strcspn(line, "\n")] = '\0'; //fgets() reads the \n character (that's when you press Enter).
read = strlen(line);
printf ("\n String from user: %s\n", line);
}else
{
printf ("Nothing read.. \n");
return -1;
}
// Now we need the same amount of byte to hold the reversed string
char* rev_line = (char*)malloc(read);
for (int i = 0, j = read-1; i < read; i , j--)
{
rev_line[i] = line[j];
}
printf("%s\n",rev_line);
free(rev_line);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/461264.html
上一篇:從二維陣列中動態獲取列
下一篇:使用for回圈構建Numpy陣列
