Welcome to the MacNN Forums.

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

You are here: MacNN Forums > Software - Troubleshooting and Discussion > Developer Center > C: String i/o question

C: String i/o question
Thread Tools
Junior Member
Join Date: Jul 2002
Location: Australia
Status: Offline
Reply With Quote
Mar 4, 2004, 07:43 PM
 
In c, how do u print a specific amout of characters from a string. I always thought it was something like this:

Code:
char test[255] = "abcdefghijk"; printf("%s\n",test[3]);
Which return "d", so this way is correct. So whats wrong with the following code:

Code:
#include <stdio.h> int main() { FILE *fp; char fileOutput[255]; int count; fp = fopen( "data.dat", "rt" ); while( !feof(fp) ) { fgets( fileOutput, 255, fp ); puts(fileOutput[2] ); } fclose(fp); return 0; }
     
Mac Elite
Join Date: Feb 2000
Location: Nashua NH, USA
Status: Offline
Reply With Quote
Mar 4, 2004, 08:35 PM
 
The array indexing notation doesn't work like that.
Code:
char array[] = "abcdef" *array == 'a' *(array+1) == 'b' array[2] == 'c'
Code:
printf("%s\n",test[3]);
results in just "d"

Your second piece of code results in just the third byte of the file.

Try snprintf or its equivalent.
     
Syphor  (op)
Junior Member
Join Date: Jul 2002
Location: Australia
Status: Offline
Reply With Quote
Mar 4, 2004, 08:39 PM
 
So how could I get a specific character out of fileOutput?

The reason i need this is because i have something similar in a function in a larger program i'm creating, and when this function reads the .dat file i want it to disregard all occurrences of "\n" and "/".

I wanted to do something like:

if (fileOutput[0]!="\n" || fileOutput[0]!="/") {
//do some stuff
} else {
//do some other stuff
}
     
Mac Elite
Join Date: Feb 2000
Location: Nashua NH, USA
Status: Offline
Reply With Quote
Mar 4, 2004, 08:58 PM
 
I din't realize you wanted a specific character. It read like you wanted to print the first n characters.


Code:
for ( i = 0; !feof(fp); ++i ) { array[ i ] = fgetc( fp ); }
fgetc gets one character at a time and moves the filepointer ahead one byte.
     
   
Thread Tools
Forum Links
Forum Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Top
Privacy Policy
All times are GMT -5. The time now is 09:00 PM.
All contents of these forums © 1995-2011 MacNN. All rights reserved.
Branding + Design: www.gesamtbild.com
vBulletin v.3.8.7 © 2000-2011, Jelsoft Enterprises Ltd., Content Relevant URLs by vBSEO 3.3.2