views:

74

answers:

3
+2  Q: 

c++ extract string

hi.

i have 26/01/10 09:20:20 MAL BIN BIN275 TSTCB U8L5 O/CR ..N UCOS Operated in string

i want to extract column 36 into 60 that is

BIN275 TSTCB U8L5 O/CR

the last output i want to include

O/CR

is there any simple solution to settle this? already make this but not work.

#include <iostream>
#include <string.h>
#include <fstream>
using namespace std;
int main()
{
FILE * pFile;
char mystring [100];
int string_length;

ofstream output;

pFile = fopen ("input.txt" , "r");
output.open("output.txt", ios:: out);


fgets (mystring , 100 , pFile);
puts (mystring);

string_length = strlen(mystring);

int i=36;

while (i < 60) 
{
output<<mystring[i];
++i;
}


fclose (pFile);
output.close();
return 0;

}

thank you

+2  A: 

Your program basically works but your column numbers are not correct. Try:

int i=26;

while (i < 48)

It gives me the result you are specifying.

Amardeep
test.c:1:20: error: iostream: No such file or directory
apis17
@apis17 What is your development environment? It should find iostream.
Vitor Py
You should name the program test.cpp.
Amardeep
i use linux. maybe could find another compiler. thank you. i will post result later.
apis17
Under Linux compile with `g++ test.cpp -o test` then execute with `./test`
Amardeep
yes it works ! thank you.
apis17
updates : this print `26/01/10 09:20:20 MAL BIN BIN275 TSTCB U8L5 O/CR ..N UCOS Operated`. the file writing correctly but the output (echo) must only `O/CR` on screen
apis17
A: 

yes i know what you mean... but for my input.txt there is no fix input, so the 4 character maybe in anywhere within the range of the column.. that why i want to remove the white space first then take the last 4 character as my final output.

abc
welcome abc :) . hope some1 will help.
apis17
+2  A: 

Since you seem to want to use C++, we could write it slightly more elegantly as:

#include <fstream>
#include <string>

int main()
{
    int const colLeft  = 36; // or 26
    int const colRight = 60; // or 48

    std::ifstream input("input.txt");
    std::ofstream output("output.txt");

    std::string  line;
    std::getline(input,line);

    output << line.substr(colLeft,(colRight-colLeft)+1);
}
Martin York