Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Not technically formatting but positioning non the less.

I am new to C++ and am trying to make a basic program that opens a text file, reads it, and displays the information like so:

Computer names, and IP's of users
ComputerName xxx.xxx.xxx.xxx UserName
ComputerName xxx.xxx.xxx.xxx UserName
ComputerName xxx.xxx.xxx.xxx UserName
etc etc

I can't seem to get the hang of what seems a pretty simple (simple...) task of working with file streams.

The basic code (before I deleted it) looked something like this.

Int main(){

char ch;
ifstream fin ("list.txt");
    while (fin.get(ch))
          {
          cout << ch;
}


Which would output the whole document, in an unformatted fashion like so
ComputerName 192.192.192.192 RandomUserName
ComputerName 192.192.192.50 OtherRandomUserName
ComputerName 192.192.192.30 SomeOtherRandomUserName

It is a simple task but no matter what I do I can not make strings of individual computer names, ip, username etc with out massive compile errors.

If someone could simply point me the right way I would be happy.

Also I tried the google machine for this but kept finding contradictory articles. eg Some would use peek() to add spacing, and others would use other methods that I couldn't find header files and what not.

Any help is appreciated.

Thanks

Signed,

Noob
Posted

Here are the steps:

1. Use istream::getline() to get an entire line from the file.
2. Construct a std::istringstream on the line data.
3. Use stream operators (>>) to extract the three strings, or use std::copy() to copy them to a std::vector<std::string>.
 
Share this answer
 
You may use ios_base::width and ios::fill for specifying the 'xxx' format, for instance

C++
#include <iostream>
using namespace std;
int main()
{
  int ip[]={192,168, 1, 20};
  cout.width(3);
  cout.fill('0');

  for (int i=0; i<sizeof(ip)/sizeof(ip[0]); i++)
  {
    if (i) cout << '.';
    cout.width(3);
    cout << ip[i];
  }
  cout << endl;
}


outputs



192.168.001.020


 
Share this answer
 
Thanks for the posts, I think I have jumped the gun a bit.

I have read a book on C++ and believed I knew enough to do this, I am going to start smaller and work to this.

I will make the app have static values rather than reading them from a file.

Thanks for the advice though.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900