0
votes

I have problem with scanf and two strings.

char city1[11], city2[11];
for(int i = 0; i < (m + k); i++) {
scanf("%s %s", city1, city2);
}

I should read (m + k) thimes two strings - names of citites. The problem is that when I write some strings an press enter nothing hapen. Pointer is on the screen but I can't do anything. I tried to write something with printf after scanf but it doesn't work. :/

More code:

int n, m, k;
do {
    scanf("%d %d %d", &n, &m, &k);
} while(n < 2 || n > 10001 || -1 < m || m > 100001 || -1 < k || k > 100001);

city* cities = (city*)malloc(n*sizeof(city));
path* paths = (path*)malloc((m + k)*sizeof(path));
int addCities = 0;
char city1[11], city2[11];
for(int i = 0; i < (m + k); i++) {
    scanf("%s %s", city1, city2);
    printf("ok");

    if(addCities < n && !isListed(cities, n, city1)) { // if city1 is not into cities
        // add it
        strcpy(cities[addCities].name, city1);
        cities[addCities].prev = NO_PARENT;
        addCities++;
    }
    paths[i].i = getCityNumber(cities, n, city1); // number of city1

    if(addCities < n && !isListed(cities, n, city2)) { // if city2 is not into cities
        // add it
        strcpy(cities[addCities].name, city2);
        cities[addCities].prev = NO_PARENT;
        addCities++;
    }
    paths[i].j = getCityNumber(cities, n, city1); // number of city2

    if(i >= m)
        scanf("%d", &paths[i].price);
}
2
Please show a complete example. - Oliver Charlesworth
This code snippet is 'C' like. Please edit your tag - A. K.
can you please give the full code ? what are and where are defined m nad k ? - zmo
I add a full main function. ;) - micobg
Don't cast the output value of malloc. - Daniel Kamil Kozar

2 Answers

2
votes

May be this condition means not what you expect:

while(n < 2 || n > 10001 || -1 < m || m > 100001 || -1 < k || k > 100001)

This will ask you for n, m, k while this condition is true. If you enter n=3,m=-1,k=-1 it will pass next.

What n, m, k ranges are valid for input?

If n >=2 && n <= 10001, m >= -1 && m <= 100001, k >= -1 && k <= 100001, then valid loop is

do {
    scanf("%d %d %d", &n, &m, &k);
} while ( n < 2 || n > 10001 || m < -1 || m > 100001 || k < -1 || k > 100001 );
1
votes

I have replaced (m+h) with the number 10 since you don't reference m or h in your code. Here is some code that looks like what you want to do. This code works.

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

int main(void){
  char city1[11], city2[11];

  for (int i=0;i<10;i++){
    scanf("%s %s",city1,city2);
    printf("city1: %s\n",city1);
    printf("city2: %s\n",city2);
  }


}

The output is like this. I entered a b c asdf c d

a b
city1: a
city2: b
c asdf
city1: c
city2: asdf
c
d
city1: c
city2: d

I hope this helps!