I want to finish a program which can find a string in a file and then output a char 'T' in the end of line which the string exists . And my code like below(in this example I just find
a string "33"):
std::fstream f("D://test.txt");
char buff[256];
while(f.getline(buff,256)){
if(strstr(buff,"33")!= nullptr){
std::cout<<buff<<std::endl;
f.unget();//point to space
f.unget();//point to end of this line
f.seekp(f.tellg());
f<<'T';
break;
}
}
But it run wrong,as the pic show .What cause this fault?
And the origin test.txt just like:
value:32 char:
value:33 char:!
value:34 char:"
value:35 char:#
value:36 char:$
value:37 char:%
value:38 char:&
value:39 char:'
And the effect I want to get just like:
value:32 char:
value:33 char:T
value:34 char:"
...
Well! thanks the comment from "Igor Tandetnik". I try mycode in vs 2022, it runs well. Actually I run my code with mingw and clion in the beginning . I think this may be a bug of mingw.
Related
[#tl;dr] I have Visual Studio Ultimate 2013 and Eclipse Neon v2(C++),
and I need to redirect the output of my program using DOS format, but
I have no idea how.
Im on Windows btw.
OK.. so I have this class assignment where I have to write a program like this:
#include <iostream>
#include <string>
using namespace std;
/* Check if the Character is lower case or not */
bool checkLowerCase(char c) {
if (c >= 'a' && c <= 'z') return true;
return false;
}
/*
* If there is any lower case letter, it will replace it will a upper case.
* example:
* "Tauros" will become "TAUROS"
* "auHU" will become "AUHU"
*/
string fixer(string s)
{
char right = ('a' - 'A');
string a = s;
for (unsigned int i = 0; i < a.length(); i++)
{
if (checkLowerCase(a[i])) {
a[i] = a[i] - right;
}
}
return a;
}
int main(void)
{
while (1) //infinite loop
{
string line;
getline(cin, line);
if (!cin) { //Professor wants us to only check end of input like this
return 0;
}
line = fixer(line);
cout << line << endl;
}
}
The input was:
aaaaaa
bbbbbb
cccccc
The output was:
aaaaaa
AAAAAA
bbbbbb
BBBBBB
cccccc
CCCCCC
Thanks for reading this far. Ok, so here's my problem.
The output is all messed up, so I need to redirect the output somewhere else (at least for testing).
I know how to do that using , , holding each line in a Array of String, reallocating if needed and then print what is on the array, but, unfortunately, my lecturer demanded us only to include and
Ohh, I dont know if it will matter, but we may not use char*, only the class string.
My lecturer told us that we have to use DOS format. But I have no clue how to do that. If someone can tell me how to do either redirect the input or the output is finee...
I have in my PC both Eclipse C++ (working glitchy) and Visual Studio Ultimate 2013 (working fine).
[Edit] Im on Windows.
AGAIN: I may only include and
For more information, here's his slide on DOS format.
*For testing purposes one redirect to/from a file
*DOS formatting will have unexpected consequences
– The end-of-line is the CR-NL combination
– A line read from the file will end with CR
– The CR character is the command to erase the
previous line!
./main < infile.txt Input is from infile.txt
./main > outfile.txt Output is to outfile.txt
./main < infile.txt > outfile.txt Both input and output are redirected
OK, so... I found instructions that helped me here:
https://msdn.microsoft.com/en-us/library/ms235639.aspx
I opened my project folder in the VisualStudio, created 2 files.
input.txt
output.txt
I opened the Developer Command Prompt for VS2013 that I had in my PC.
cd ["C://my_project_path"] //go to my project folder
cl /EHsc file.cpp
/*
cl /EHsc will compile my program (I think it only compiles one file at a time.
I have yet to test it).
*/
file < input.txt > output.txt // this command will run my program
So when I run my program like this... Instead of waiting for an input from keyboard, my program will read input.txt as the standard input. And when I try to print something to the output, it will write on the output.txt instead.
[EDIT] at the end of the link I pasted, there are explanations on how to compile multiple files and what exacly does the /EHsc do exacly
EDIT: Problem solved! Turns out Windows 7 wont let me read/ write to files without explicitly running as administrator. So if i run as admin it works fine, if i dont i get the weird results i explain below.
I've been trying to get a part of a larger program of mine to read a file.
Despite trying multiple methods(istream::getline, std::getline, using the >> operator etc) All of them return with either /0, blank or a random number/what ever i initialised the var with.
My first thought was that the file didn't exist or couldn't be opened, however the state flags .good, .bad and .eof all indicate no problems and the file im trying to read is certainly in the same directory as the debug .exe and contains data.
I'd most like to use istream::getline to read lines into a char array, however reading lines into a string array is possible too.
My current code looks like this:
void startup::load_settings(char filename[]) //master function for opening a file.
{
int i = 0; //count variable
int num = 0; //var containing all the lines we read.
char line[5];
ifstream settings_file (settings.inf);
if (settings_file.is_open());
{
while (settings_file.good())
{
settings_file.getline(line, 5);
cout << line;
}
}
return;
}
As said above, it compiles but just puts /0 into every element of the char array much like all the other methods i've tried.
Thanks for any help.
Firstly your code is not complete, what is settings.inf ?
Secondly most probably your reading everything fine, but the way you are printing is cumbersome
cout << line; where char line[5]; be sure that the last element of the array is \0.
You can do something like this.
line[4] = '\0' or you can manually print the values of each element in array in a loop.
Also you can try printing the character codes in hex for example. Because the values (character codes) in array might be not from the visible character range of ASCII symbols. You can do it like this for example :
cout << hex << (int)line[i]
I'm new to programming in c++ and I'm facing a problem following lynda.com tutorials. It seems okay on the tutorial video but this isnt working with me.
#include <stdio.h>
enum { max_string = 127 };
static char string[max_string + 1 ] = "";
int main( int argc, char ** argv ) {
printf("Type a string: ");
fgets(string, max_string, stdin);
printf("The string is %s", string);
return 0;
}
And when I run this something blank appears and I need when I right something like "hey" in the blanket space, this happens:
hey
Type a string: The string is hey
This is completely strange for me and I have no idea what Im doing wrong tbh.
I'm using Eclipse btw.
Could someone help me out?
It appears that your standard output stream is line-buffered, meaning that text you print doesn't appear until you've printed a complete line. It should be unbuffered if you're writing to an interactive device; perhaps something is preventing the system from being aware that the output device is interactive.
Adding
fflush(stdout);
after your first printf should force the "Type a string: " prompt to appear immediately (and even if your output is unbuffered, fflush(stdout) is harmless).
I was about to suggest changing your second printf from:
printf("The string is %s", string);
to:
printf("The string is %s\n", string);
to ensure that your program's output ends with a newline (some systems can misbehave if it isn't) -- but fgets() actually leaves the newline in your string (unless the input line was very long). Eventually you'll want to be able to deal with that kind of thing.
In the below code i would like to also ignore the character ” . But after adding that in i still get “Mr_Bishop” as my output.
I have the following code:
ifstream getfile;
getfile.open(file,ios::in);
char data[256];
char *line;
//loop till end of file
while(!getfile.eof())
{
//get data and store to variable data
getfile.getline(data,256,'\n');
line = strtok(data," ”");
while(line != NULL)
{
cout << line << endl;
line = strtok(NULL," ");
}
}//end of while loop
my file content :
hello 7 “Mr_Bishop”
hello 10 “0913823”
Basically all i want my output to be :
hello
7
Mr_Bishop
hello
10
0913823
With this code i only get :
hello
7
"Mr_Bishop"
hello
10
"0913823"
Thanks in advance! :)
I realise i have made an error in the inner loop missing out the quote. But now i receive the following output :
hello
7
Mr_Bishop
�
hello
10
0913823
�
any help? thanks! :)
It looks like you used Wordpad or something to generate the file. You should use Notepad or Notepad++ on Windows or similar thing that will create ASCII encoding on Linux. Right now you are using what looks like UTF-8 encoding.
In addition the proper escape sequence for " is \". For instance
line = strtok(data," \"");
Once you fix your file to be in ASCII encoding, you'll find you missed something in your loop.
while(!getfile.eof())
{
//get data and store to variable data
getfile.getline(data,256,'\n');
line = strtok(data," \"");
while(line != NULL)
{
std::cout << line << std::endl;
line = strtok(NULL," \""); // THIS used to be strtok(NULL," ");
}
}//end of while loop
You missed a set of quotes there.
Correcting the file and this mistake yields the proper output.
Have a very careful look at your code:
line = strtok(data," ”");
Notice how the quotes lean at different angles (well mine do, I guess hopefully your font shows the same thing). You have included only the closing double quote in your strtok() call. However, Your data file has:
hello 7 “Mr_Bishop”
which has two different kinds of quotes. Make sure you're using all the right characters, whatever "right" is for your data.
UPDATE: Your data is probably UTF-8 encoded (that's how you got those leaning double quotes in there) and you're using strtok() which is completely unaware of UTF-8 encoding. So it's probably doing the wrong thing, splitting up the multibyte UTF-8 characters, and leaving you with rubbish at the end of the line.
I have a simple C++ program that reads stdin using scanf and returns results to stdout using printf:
#include <iostream>
using namespace std;
int main()
{
int n, x;
int f=0, s=0, t=0;
scanf("%d",&n); scanf("%d",&x);
for(int index=0; index<n; index++)
{
scanf("%d",&f);
scanf("%d",&s);
scanf("%d",&t);
if(x < f)
{
printf("first\n");
}
else if(x<s)
{
printf("second\n");
}
else if(x<t)
{
printf("third\n");
}
else
{
printf("empty\n");
}
}
return 0;
}
I am compiling with g++ and running under linux. I execute the program using a text file as input, and pipe the output to another text file as follows:
program < in.txt > out.txt
The problem is that out.txt looks like this:
result1_
result2_
result3_
...
Where '_' is an extra space at the end of each line. I am viewing out.txt in gedit.
How can I produce output without the additional space?
My input file looks like this:
2 123
123 123 123
123 234 212
Edit: I was able to find a workaround for this issue: printf("\rfoo");
Thanks for your input!
Try removing the '\n' from your printf() statements, and run the code again. If the output file looks like one long word (no spaces), then you know that the only thing being inserted after the text is that '\n'.
I assume that the editor you are using to read the out.txt file just makes it look like there is an extra space after the output.
If you are still unsure, you can write a quick program to read in out.txt and determine the ASCII code of each character.
The end of line chars are:
System Hex Value Type
Mac 0D 13 CR
DOS 0D 0A 13 10 CR LF
Unix 0A 10 LF
For a end of line on each system you can:
printf("%c", 13);
printf("%c%c", 13, 10);
printf("%c", 10);
You can use this like
printf("empty");
printf("%c", 10);
Wikipedia Newline article here.
Okay, it's a little hard to figure this out, as the example program has numerous errors:
g++ -o example example.cc
example.cc: In function 'int main()':
example.cc:19: error: 'k' was not declared in this scope
example.cc:22: error: 'o' was not declared in this scope
example.cc:24: error: 'd' was not declared in this scope
make: *** [example] Error 1
But it's not going to be your input file; your scanf will be loading whatever you're typing into ints. This example, though:
/* scan -- try scanf */
#include <stdio.h>
int main(){
int n ;
(void) scanf("%d",&n);
printf("%d\n", n);
return 0;
}
produced this result:
bash $ ./scan | od -c
42
0000000 4 2 \n
0000003
on Mac OS/X. Get us a copy of the code you're actually running, and the results of od -c.
More information is needed here, as timhon asked, which environment are you working under? Linux, Windows, Mac? Also, what text editor are you using which displays these extra spaces?
My guess is that your space isn't really a space. Run
od -hc out.txt
to double check that it is really a space.
First, the code sample you've given doesn't compile as o and d are not defined...
Second, you've probably got whitespace at the end of the line you're reading in from the input file. Try opening it in vi to see. Otherwise, you can call a trim function on each line prior to output and be done with it.
Good luck!
Make sure you're looking at the output of the program you expect; this has a syntax error (no ";" after int n).
I feel like it's not even close to this, but if you run this on Windows, you'll get \r\n as line terminators, and, maybe, under *nix, under a non-Windows-aware text editor, you'll get \r as a common blank space, since \r is not printable.
Long shot, the best way to test this is using an hexadecimal editor and see the file yourself.