User Tools

Site Tools


cs_lang:c

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
cs_lang:c [2011/07/12 10:37] cedriccs_lang:c [2012/09/30 23:32] (current) cedric
Line 15: Line 15:
 { {
     printf("Hello World");     printf("Hello World");
- 
- 
 } }
 </code> </code>
Line 28: Line 26:
  
 $ ./hello.out  $ ./hello.out 
-Hello Worldcedric +Hello World 
-<code>+</code> 
 + 
 + 
 +===== Increment a number ===== 
 +<code c> 
 +#include "stdio.h" 
 + 
 +char  line[100]; 
 +int   value; 
 + 
 +int main() 
 +
 +    printf("Enter a value:"); 
 +    fgets(line, sizeof(line), stdin); 
 +    sscanf(line, "%d", &value); 
 + 
 +    printf("Inc: %d\n", value + 1); 
 + 
 +    return 0; 
 +
 +</code> 
 + 
 +<code bash> 
 +$ gcc -Wall test1.c  
 +cedric@debian:~$ ./a.out  
 +Enter a value:41 
 +Inc: 42 
 +</code> 
 + 
 +==== Equivalent in python ==== 
 +<code python> 
 +>>> def inc(): 
 +...     value = raw_input("Enter a value:"
 +...     print "Inc:", int(value)+1 
 +...  
 +>>> inc() 
 +Enter a value:41 
 +Inc: 42 
 +</code>
  
  
Line 35: Line 71:
 ===== Read a file ===== ===== Read a file =====
 <code c> <code c>
-#include <iostream.h> +#include <stdio.h>   /* required for file operations */
-#include <fstream.h>+
  
-int main ()+FILE *fr;            /* declare the file pointer */ 
 + 
 +main()
 { {
-        //  Open the file +   char line[1024]; 
-        ofstream inputFile ("./file.txt", ios::in); +   fr = fopen ("./file.txt", "rt");  /* open the file for reading *
-        // Test +   /* "rtmeans open the file for reading text */ 
-        if (!inputFile) + 
-        { +   while(fgets(line, 1024, fr!= NULL
-                cerr << "Error<< endl; +   
-                exit (1); +         printf ("%s\n"line); 
-        } +   
-        char buf [1024]; +   fclose(fr);  /* close the file prior to exiting the routine */
-        //  Until there are no more lines in the file, +
-        //  read and display it. +
-        while (!inputFile.eof()) +
-        +
-                inputFile.getline (buf,1024);+
-                cout << buf << endl;; +
-        +
-        // Close the file +
-        inputFile.close ();;+
 } }
 </code> </code>
  
-===== Equivalent in python =====+==== Equivalent in python ====
 <code python> <code python>
 for line in open("./file.txt", "r"): for line in open("./file.txt", "r"):
     print line     print line
 </code> </code>
cs_lang/c.1310459830.txt.gz · Last modified: 2011/07/12 10:37 by cedric