0

In C++, I can read a matrix with something like

int main()
{
    int i,j,k,n;
    float a[10][10]={0},d;
    clrscr();
    cout<<"No of equations ? "; cin>>n;
    cout<<"Read all coefficients of matrix with b matrix too "<<endl;
    for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
            cin>>a[i][j];
    ...
return 0;}

in C I cannot use

#include <iostream>

and related functions as

- clrscr(); 
- cout<<
- cin>>

How should I fix my code to work in c?

Mat
  • 202,337
  • 40
  • 393
  • 406
AndreaF
  • 11,975
  • 27
  • 102
  • 168
  • @40two could you give me a sample of use of `scanf()` in my case? Thanks – AndreaF May 19 '14 at 23:29
  • `man 3 scanf`: http://linux.die.net/man/3/scanf – chrk May 19 '14 at 23:32
  • 3
    Note, [`clrscr()` is not an *iostream* or C++ `std::` function](http://stackoverflow.com/questions/930138/is-clrscr-a-function-in-c). It's not standard in C either, it usually comes from non-standard *conio.h* header, when it is used. So that will work (or not) just the same in C and C++, though you may need to add the relevant library if it's not included in the build by default. – hyde May 20 '14 at 06:09

2 Answers2

3

For simple cases like this, using scanf() is not rocket science:

if (scanf("%d", &n) != 1)
    …report unexpected EOF or format error…
if (n > 10)
    …report that n is too big…

for (i = 1; i <= n; i++)
    for (j = 1; j <= n; j++)
        if (scanf("%f", &a[i][j]) != 1)
            …report unexpected EOF or format error…

Use %f because a is an array of float. Check that you got a value each time you try to read one. You can capture the return from scanf() if you want to distinguish between (premature) EOF and format error.

OTOH, in more complex scenarios, scanf() is extremely hard to use correctly. Use with caution. Consider using fgets() or getline() along with sscanf(); it is often easier to control the input handling and usually improves the error reporting.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • The program execution stops at this codeline `float a[10][10]={0},d;` without compilation error..why? – AndreaF May 20 '14 at 15:35
  • @AndreaF: There is no obvious reason for the code to stop at that line. The next line is a `clrscr()` call; I wonder if that's what it stopped on? Otherwise, the code should be OK as long as there is input from standard input — either because you're typing or because you redirected it from file. (Did you keep the prompts — or, rather, change the prompts to `printf("No of equations? ");`? If you didn't do that, then it is hanging waiting for you to type the number of equations to the `if (scanf("%d", &n) != 1)` line.) – Jonathan Leffler May 20 '14 at 16:24
  • Might `float a[10][10]={0}` fail on old compilers? – chux - Reinstate Monica May 20 '14 at 18:28
  • @chux: if you mean positively archaic (pre-C89), then yes -- initializing automatic aggregates was added to the C89 standard, AFAICR. Having said that, one of the changes listed in C99 was 'relaxed constraints on aggregate and union initialization', so it could be a problem. (OTOH, the OP indicated that the code compiled OK and failed at runtime, so the problem is unlikely to be this.) – Jonathan Leffler May 20 '14 at 19:02
2

Here you go:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int n, i, j;
  double **M;
  // prompt the user to enter number of equations
  printf("Enter # of equations:");
  if (scanf("%d", &n) != 1 && n > 0) exit(1);
  // allocate square n x n matrix
  M = (double**) malloc(sizeof(double*) * n);
  for (i = 0; i < n; ++i) M[i] = (double*)malloc(sizeof(double)* n);
  // prompt user to enter matrix coefficients
  printf("Read all coefficients of matrix with b matrix too\n");
  for (i = 0; i < n; ++i) {
    for (j = 0; j < n; ++j) {
      if (scanf("%lf", &(M[i][j])) != 1) exit(1);
    }
  }
  // print values of matrix
  for (i = 0; i < n; ++i) {
    for (j = 0; j < n; ++j) {
      printf("%lf ", M[i][j]);
    }
    printf("\n");
  }
  // free allocated memory
  for (i = 0; i < n; ++i) {
    free(M[i]);
  }
  free(M);

  return 0;
}
101010
  • 41,839
  • 11
  • 94
  • 168
  • What's with scrunching everything into as few lines as possible? Why not write it all on three lines (two `#include` lines plus everything else on the third). – Jonathan Leffler May 19 '14 at 23:41
  • @JonathanLeffler Sorry dude I'm not a native speaker what's "scrunching" means? – 101010 May 19 '14 at 23:44
  • _scrunch_ (verb): 2. • become crushed or squeezed into a compact mass. My question is 'why so many lines with two statements on one line', or 'why not use a little vertical space to make the code more readable'. (I might also add — (1) check return from `malloc()`, (2) show how to deallocate the space, and (3) why not go with static allocation as in the question?) – Jonathan Leffler May 19 '14 at 23:48
  • why replace the simple `float a[10][10] = {0};` with all that guff? – M.M May 20 '14 at 00:29
  • 1
    @MattMcNabb Maybe for the user to be able to give arbitrary sizes of matrices... just a thought... Apparently, extensibility is not your concern. – 101010 May 20 '14 at 06:01
  • use `float a[n][n]` then – M.M May 20 '14 at 08:10
  • @MattMcNabb `n` is known at runtime you can't do `float a[n][n]`. – 101010 May 20 '14 at 08:41
  • @40two `int main() { int n; if ( scanf("%d", &n) != 1 || n < 1 ) return 0; float foo[n][n]; }` – M.M May 20 '14 at 08:54
  • 1
    @40two: C99 unconditionally and C11 conditionally supports VLAs, variable length arrays, where the dimension is known only at runtime. Such arrays cannot be global or static variables, but that isn't a problem here. – Jonathan Leffler May 20 '14 at 15:01