I have multiple different parts of data that I am trying to combine into one single array, as though I'm writing a string to it and am trying to find a method of doing so. My current attempt is shown below, but of course doesn't work. I was hoping someone could point me into the correct direction
newline = "%s %s\t%d\t%d %d %d \t%.2f\n",
arr_student[printing].fname, arr_student[printing].sname, arr_student[printing].UP_no, arr_student[printing].marks_1,
arr_student[printing].marks_2, arr_student[printing].marks_3, arr_student[printing].average_mark;
If you're trying to create a string with that information, you should use the sprintf function which will generate a string according to your format string and format parameters:
Edit: As pointed out by #PeteKirkham, you should use the snprintf function instead, which allows you to specify the maximum number of bytes (or characters) to write to the output string
char newline[100]; // or however many characters you want to allocate for
snprintf(newline, 100, "%s %s\t%d\t%d %d %d \t%.2f\n",
arr_student[printing].fname, arr_student[printing].sname, arr_student[printing].UP_no, arr_student[printing].marks_1,
arr_student[printing].marks_2, arr_student[printing].marks_3, arr_student[printing].average_mark); // again, replace 100 with however many characters you are expecting to write
Related
I am currently trying to read from multiple directories, but when I set the path using a %s (has a saved array of all the file locations) it will not read.
SDL_Surface* image = SDL_LoadBMP("D:\\UltimateModManager\\mods\\%s\\.umm\\icon.bmp", currentmod[i - 1]);
It prints the location just fine onto the console, yet it will not read my image. But if I set a true path, it does oddly enough.
You seem to have a misconception that %s in a string has some special property. It doesn't. The % character is just a literal %. The context in which you've used it the way you seem to want is passing it to printf, where it's *still just a literal % in the string, but the string is a format string that printf interprets to know what types of arguments to expect and how to format them, rather than a string to be printed itself.
To achieve what you want here, you need to use an additional buffer array to construct your string in, and use something like:
snprintf(buf, sizeof buf,
"D:\\UltimateModManager\\mods\\%s\\.umm\\icon.bmp",
currentmod[i - 1]);
then pass buf as the argument to SDL_LoadBMP.
When a scanf("%s",s); (one of many ways to get a string which is not perfect) encounters a space in the input, it will try to put it in another variable, right? But what hapens if there is only one variable provided as in this case?
Also what other ways are used to input a string? which is the esiest or best one to use and which one does not give problems like the gets(s); function?
Here is my s_insert function now:
// pointer to pointer needed when you allocate memory in the function
void s_insert(char **string_one){ //inserts string (loss of original data)
*string_one=(char*)malloc(200);
fgets (*string_one,200,stdin);
}
scanf for %s data specification reads characters before first space symbol (' ', '\n' or '\t'). If you want to read string with spaces (more than two words) use fgets function, that is more safe than 'gets' because you can set the maximum number of character that can be allocated in your memory and avoid segmentation fault.
No, it will only try to "put in a variable" when it encounters a % with a suitable conversion specifier in the first argument. That argument is what controls its behavior, not the input.
Having a single %s and multiple words in the input will simply leave the remaining words still in the input buffer, since scanf() will stop when it's done with the single %s, it has nothing more to do then.
It reads its conversion specification string and tries to read input to match that, not the other way around.
I have a text file full of points of the following format on different lines
LONG,LONG
i can successfully read each line and print it out, but I how can I parse the string in C such that I get each long of each point on its own?
Thanks!
if you have the line already, it's easiest to use sscanf() to do this:
long a, b;
if(sscanf(line, "%ld,%ld", &a, &b) == 2)
{
/* Successfully parsed two long integers, now store them somewhere I guess. */
}
Note that it's a good idea to check the return value of sscanf(), this protects you from wrongly accepting illegal data and getting undefined results.
You can do it in multiple steps too if you need more control, as #dasblinkenlights suggested. You can use strtol() to parse the first number from the start of the line, then if that succeeds look for the comma, and then parse the second number. It can be faster than sscanf(), but I wouldn't expect too much for something this simple.
There are many solutions to this.
One is to read the line, read the first long with strtol find the position of the comma that follows with strchr, and read the second number from there.
Another solution would be to read the line, and pass it to sscanf function with the format that accepts two comma-separated LONGs.
Use the string variant of scanf() if you say you've already got the line:
char* line;
long long1;
long long2;
sscanf(line, "%ld,%ld", &long1, &long2);
Indeed as #unwind suggests in his +1 answer, it's a very good idea to check the return value of scant(), which is the number of successfully read values.
I have a file that contains 80 characters per line. I want to go to a particular line that starts with "ATOM".
I tried with fscanf(f1," %s%*[^\n]", rec) and compare rec with strcmp(rec,"ATOM"), but it reads the next line from the match.
I also tried with fscanf("line_format", variables), but this reads somewhere else from the file.
The line is
ATOM 1 N MET A 1 36.643 -24.862 8.890 1.00 24.11 N
From this I want to read character by character and assign it to variables. I have a problem with the float values and spaces. If I find a space in a place of particular variable how do I read it? How do I read the float values if there is no space between them?
You can read each line from the input file using fgets(), tokenise it using strtok() or strtok_r(), compare the first token to "ATOM", and then parse the rest of the tokens using atof() or atoi() to convert them to floating point or integer numbers if necessary.
Although this is a bit of an overkill since the ATOM record in the PDB file has a well defined structure with fixed sized fields and any conformant pdb file would be much easier to parse. You just pick the relevant substrings and pass them to atof() or atoi().
I believe you had an error in your (not shown) line_format. You really should be able to just do:
if( fscanf(f1, "ATOM %d %s %s %s %d %f %f %f %f %f %s", /* ... */) == 11 )
{
/* store/analyze/print the parsed values */
}
Note of course that this runs the risk of overwriting the string arguments. You could use a more specific format string to limit the lengths.
I am having trouble accepting input from a text file. My program is supposed to read in a string specified by the user and the length of that string is determined at runtime. It works fine when the user is running the program (manually inputting the values) but when I run my teacher's text file, it runs into an infinite loop.
For this example, it fails when I am taking in 4 characters and his input in his file is "ABCDy". "ABCD" is what I am supposed to be reading in and 'y' is supposed to be used later to know that I should restart the game. Instead when I used scanf to read in "ABCD", it also reads in the 'y'. Is there a way to get around this using scanf, assuming I won't know how long the string should be until runtime?
Normally, you'd use something like "%4c" or "%4s" to read a maximum of 4 characters (the difference is that "%4c" reads the next 4 characters, regardless, while "%4s" skips leading whitespace and stops at a whitespace if there is one).
To specify the length at run-time, however, you have to get a bit trickier since you can't use a string literal with "4" embedded in it. One alternative is to use sprintf to create the string you'll pass to scanf:
char buffer[128];
sprintf(buffer, "%%%dc", max_length);
scanf(buffer, your_string);
I should probably add: with printf you can specify the width or precision of a field dynamically by putting an asterisk (*) in the format string, and passing a variable in the appropriate position to specify the width/precision:
int width = 10;
int precision = 7;
double value = 12.345678910;
printf("%*.*f", width, precision, value);
Given that printf and scanf format strings are quite similar, one might think the same would work with scanf. Unfortunately, this is not the case--with scanf an asterisk in the conversion specification indicates a value that should be scanned, but not converted. That is to say, something that must be present in the input, but its value won't be placed in any variable.
Try
scanf("%4s", str)
You can also use fread, where you can set a read limit:
char string[5]={0};
if( fread(string,(sizeof string)-1,1,stdin) )
printf("\nfull readed: %s",string);
else
puts("error");
You might consider simply looping over calls to getc().