gpt4 book ai didi

c - 将字符串读入 char 数组,然后获取字符串的大小

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:40 24 4
gpt4 key购买 nike

我正在做一个项目,但我对这部分感到困惑。

我需要从 stdin 读取单词并将它们放在一个 char 数组中,并使用一个指针数组指向每个单词,因为它们会呈锯齿状。其中 numwords 是一个代表字数的整数。

    char words[10000];
char *wordp[2000];

问题是我只能使用指针来添加单词。我不能再使用 [] 来帮助了。

    *wordp = words; //set the first pointer to the beginning of the char array. 
while (t < numwords){
scanf("%s", *(wordp + t)) //this is the part I dont know
wordp = words + charcounter; //charcounter is the num of chars in the prev word
t++;
}

for(int i = 0;words+i != '\n';i++){
charcounter++;
}

任何帮助都会很棒我对指针和数组很困惑。

最佳答案

如果您使用额外的指针,您的代码将更易于管理直接引用并增加它。这样你就不必做任何事情心理数学。此外,您需要在递增引用之前读取下一个字符串时,scanf 不会为您移动指针。

char buffer[10000];
char* words[200];

int number_of_words = 200;
int current_words_index = 0;

// This is what we are going to use to write to the buffer
char* current_buffer_prt = buffer;

// quick memset (as I don't remember if c does this for us)
for (int i = 0; i < 10000; i++)
buffer[i] = '\0';

while (current_words_index < number_of_words) {

// Store a pointer to the current word before doing anything to it
words[current_word_index] = current_buffer_ptr;

// Read the word into the buffer
scanf("%s", current_buffer_ptr);

// NOTE: The above line could also be written
// scanf("%s", words[current_word_index]);

// this is how we move the buffer to it's next empty position.
while (current_buffer_ptr != '\n')
current_buffer_ptr++;

// this ensures we don't overwrite the previous \n char
current_buffer_ptr++;

current_words_index += 1;
}

关于c - 将字符串读入 char 数组,然后获取字符串的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15536014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com