我是 C 的新手。我一直在我找到的一本書中進行練習,并且在理解字串方面遇到了很多麻煩。對于這個程式,我只是試圖反轉從用戶輸入中讀取的字串。
我目前擁有的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 300
void reverseStr(char *str, int len){
int i;
char temp[len];
for (i = len; i >= 0; i--){
strncat(temp, &str[i], 1);
}
strcpy(str, temp);
}
int main(){
char *buffer;
size_t buffsize = 32;
size_t characters;
while (characters != 1){
buffer = (char *)malloc(buffsize * sizeof(char));
if ( buffer = NULL){
perror("Unable to allocate buffer");
exit(1);
}
printf("Type something: ");
characters = getline(&buffer, &buffsize, stdin);
printf("%zu characters were read.\n", characters);
printf("You typed: %s", buffer);
reverseStr(buffer, buffsize);
printf("backwards: %s\n", buffer);
}
}
我目前所擁有的確實反轉了字串,但它也預先考慮了一堆我認為一開始是空字符的內容。
示例輸入/輸出:
Type something: sdf
4 characters were read.
You typed: sdf
backwards: 0s????
fds
如您所見,sdf確實回傳fds了它應該回傳的值,但是在它前面添加了多余的不需要的字符。
為了進一步增加我的困惑,我之前在我制作的另一個程式中讓它正常作業。
/* This should be compiled with -ansi flag */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 3000
void reverseStr(char str[MAX], int len);
int getline(char s[], int lim);
int main(){
/* Read below on why we use a char array instead of a string,
* it's very important we understand this */
char line[MAX];
int len = strlen(line)-1;
while((len=getline(line, MAX))>0){
len = strlen(line)-1;
reverseStr(line, len);
printf("%s\n", line);
}
}
void reverseStr(char str[MAX], int len){
int i;
char temp[len];
for (i = len; i >= 0; i--){
strncat(temp, &str[i], 1);
}
strcpy(str, temp);
}
int getline(char s[],int lim){
int i,c;
for(i=0;i<lim-1 && (c=getchar())!=EOF && c!='\n'; i)
s[i] = c;
if( c == '\n')
{
s[i]=c;
i;
}
s[i]='\0';
return i;
}
第二個程式的輸出:
sdf
fds
sdfsdfsdf
fdsfdsfds
The getline() in the second program is taken straight from the book. I'm guessing this must be an old, deprecated way of doing things though? It appears to be a built-in function in later versions of C.
uj5u.com熱心網友回復:
只需反向復制字符,然后在末尾添加一個 NULL 終止位元組,就可以更輕松地完成此操作。
#include <stdio.h>
#include <string.h>
void reverse_string(char *str, char *rev_str) {
int j = 0, i;
for (i = strlen(str) - 1; i >= 0; i--) {
rev_str[j ] = str[i];
}
rev_str[j] = '\0';
}
int main() {
char *str = "123456789";
char rev_str[strlen(str)];
printf("%s\n", str);
reverse_string(str, rev_str);
printf("%s\n", rev_str);
return 0;
}
輸出:
123456789
987654321
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/403636.html
標籤:
