如何重复Scanf并替换值?

问题描述 投票:0回答:1
char *stack[13];
char INteger[100];
int top = -1;


int main () {
int current = 0;


    while (current < 2) {  

        Yfunc();
        printf("cell zero %s \n", stack[0]);
        printf("cell one %s \n", stack[1]);


void Yfunc() {

    printf("Please enter a string: \n");
    scanf("%s", INteger);
    push(INteger);

}
}

char *push(char input[]) {
     top++;
     stack[top] = input;
 }

基本上,用户应该键入一个字符串,比方说“牛”。然后将该字符串推入堆栈(可行)。但是,当我第二次按下时,堆栈变得一团糟。我假设我不能多次scanf(INteger)?如果没有,对此有什么解决方法?

c stack scanf
1个回答
1
投票

所以您的stack正在保存内存地址,但实际上不复制内容。解决方案可能是这样:

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

char stack[13][100];
char INteger[100];
int top = -1;

void push(char* input) {
   memcpy(stack[++top], input, 100);
}

void Yfunc() {
  printf("Please enter a string: \n");
  scanf("%s", INteger);
  push(INteger);
}

int main () {
  int current = 0;

  while (current++ <= 2) {  
        Yfunc();
        printf("cell zero %s \n", stack[0]);
        printf("cell one %s \n", stack[1]);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.