• 0

C++...


Question

trying a simple program...open a file, read and display the information in it...the program runs, and doesn't give me any errors whatsoever, but doesn't display the proper result either...what could be wrong??

#include "stdafx.h"

#include

#include

#include

#include

#include

int main()

{

ifstream Database("db.txt", ios::nocreate);

int ArtistNum = 0;

if (Database.fail())

{

cout << "File could not be opened";

return 0;

}

else

{

String TempArtist;

while (getline(Database, TempArtist))

{

cout << TempArtist << endl;

ArtistNum++;

}

return 0;

}

}

Link to comment
https://www.neowin.net/forum/topic/20293-c/
Share on other sites

Recommended Posts

  • 0

This worked for me. I don't know what string library you're using, but I used just and it worked fine.

&lt;pre&gt;

#include &lt;iostream&gt;

#include &lt;stdio&gt;

#include &lt;fstream&gt;

#include &lt;string&gt;



//---------------------------------------------------------------------------

using namespace std;



int main()

{

  ifstream DB("db.txt");

  if(!DB){

   cout &lt;&lt; "File couldn't be opened" &lt;&lt; endl;

  }

  else

  {

    cout &lt;&lt; "File opened!" &lt;&lt; endl;

    string dbtxt;

    while(!DB.eof())

    {

      getline(DB, dbtxt);

      cout &lt;&lt; dbtxt &lt;&lt; endl;

    }

  }

  return 0;

}

&lt;/pre&gt;

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-170801
Share on other sites

  • 0

here's what i'm trying to do...

i want to get the program to load artist names (one artist per line) into an array, so it's like

Input file..

U2

Celine Dion

Weezer

...

...

Array....

ArtistArray[0] = U2

ArtistArray[1] = Celine Dion

AritstArray[2] = Weezer

...

...

Now, since C++ doesn't have string arrays, I'm guesing that I'd have to use a 2D character array...in which 1st element would be the counter, and the 2nd element would be an array of characters for the name of the artist..

How do I go about doing that??...

Just to let you guys know...this is NOT for any school related thing, just a simple little application that I'm making (TRYING to make) myself to organize my mp3s a bit more...

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171343
Share on other sites

  • 0

You can do this. This is best option!!!

#include

#include

vector artists;

artists.resize(size) //change size at any time. Number of artists.

artist[1]="Celine Dion"

or you can do:

char artists[number_of_artists][50]; //names can be up to 50 long

cout<

artist[1][2]='g'; //set the 3rd letter of the 2nd artist.

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171353
Share on other sites

  • 0

If you don't mind the stigma of using MFC, it has a CStringArray, and a CStdioFile which could prove usefull.

&lt;pre&gt;

CStdioFile fileMp3;

if (fileMp3.Open(_T("db.txt"), CFile::modeRead) == TRUE)

{

	CStringArray sArtistList;

	CString sLine;



	while(fileMp3.ReadString(sLine) == TRUE)

  sArtistList.Add(sLine);



	fileMp3.Close();

}

&lt;/pre&gt;

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171364
Share on other sites

  • 0

Using Goalie's suggestion to use a vector, you could also write it like so.

&lt;pre&gt;

#include &lt;iostream&gt;

#include &lt;stdio&gt;

#include &lt;fstream&gt;

#include &lt;string&gt;

#include &lt;vector&gt;

//---------------------------------------------------------------------------

using namespace std;



int main()

{

  vector&lt;string&gt; artists;

  ifstream DB("db.txt");

  if(!DB){

   cout &lt;&lt; "File couldn't be opened" &lt;&lt; endl;

  }

  else

  {

    cout &lt;&lt; "File opened!" &lt;&lt; endl;

    string dbtxt;

    while(!DB.eof())

    {

      getline(DB, dbtxt);

      artists.push_back(dbtxt);

      artists.resize(artists.size()+1);

    }

    for(unsigned int i=0; i &lt; artists.size(); ++i)

      cout &lt;&lt; artists[i] &lt;&lt; endl;



  }

  return 0;

}

&lt;/pre&gt;

If you're already doing that, way to go! :) If you want a sorted vector, just use the sort function in like so...

&lt;pre&gt;

  sort(artists.begin(), artists.end());

&lt;/pre&gt;

For storing line position, use fstream::pos_type pos= DB.tellg(); while doing your getline. Then use DB.seekp(pos) to get the stored line position. I hope that is what you meant.

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171475
Share on other sites

  • 0

thanks again!...

weenur, that was what i was doing myself :)

another question...

i'm trying to open another file, in which i want to begin reading line from the 39th character of the 6th line and onwards...so at every line, i begin reading from the 39th character.

if (!SongList)

cout << "File could not be opened";

else

{

int i = 0;

while (!SongList.eof())

{

while (i!=5)

{

getline(SongList, Temp);

cout << Temp << endl;

i++;

if (i==5)

break;

}

SongList.seekg(39);

getline(SongList, Temp);

cout << Temp << endl;

}

}

in this code...i managed to get to the 6th line without any problem, but when i did: getline(SongList, Temp); again (after the nested while loop)...it outputs the second line again...what should I do??

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171490
Share on other sites

  • 0

void GotoLineNumber(int LineNumber){

SongList.seekg(0);

for(int n=1;n

SongList.ignore(400,'n'); //ignores until 400 char or 'n' is read

};

}

GotoLineNumber(6); //goes to line 6.

SongList.seekg( SongList.tellg() + 39);

or try this:

SongList.seekg(39,ios::cur); goes to 39 with respect to current position.

SongList.getline(temp);

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171496
Share on other sites

  • 0

Thanks again!

Another question...

I want to make a character array of the first element in my string array

For example...

ArtistArray[0] = {"Weezer"}

CharArtist[] = {'W','e','e','z','e','r','n'}

I tried to create a character array using vectors..

vector CharArtist = ArtistArray[0];

that gave me the following error:

error C2440: 'initializing' : cannot convert from 'std::string' to 'std::vector<_Ty,_Ax>'

with

[

_Ty=char,

_Ax=std::allocator

]

----------------------------------------------------------------------------

Then I tried to create using normal character array

char CharArtist[] = ArtistArray[0];

that gave me the following error

error C2440: 'initializing' : cannot convert from 'std::string' to 'char []'

...........what should I do??

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171545
Share on other sites

  • 0

Never make a vector out of chars, use a string instead.

This will turn the string into a usuable format where only char array strings can be used.

Name.c_str()

Note: It adds a null to end of string. Even if there are null before before the end, it copies everything after too.

eg:

#include

#include //old c io. must use char array

int main(){

string hello = "Hello World";

printf(%s",hello.c_str()); //turn hello into char array.

return 0;

}

Output is "Hello" but string returned is "Hello World"

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171607
Share on other sites

  • 0

Just do this:

&lt;pre&gt;

for (int n=0;n&lt;number_of_artist;n++){

cout&lt;&lt;string[n]&lt;&lt;endl;

}&lt;/pre&gt;

If you need the string in a char array format, use ArtistArray[n].c_str();

cout<

Why unsigned. It does same thing as int when accessing elements in an array, it just takes longer to type.

cout<

cout<

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171661
Share on other sites

  • 0

You can access characters individually.

&lt;pre&gt;

vector&lt;string&gt; hello(2);

hello[1]="Hello";

cout&lt;&lt;hello[1][0]; 

&lt;/pre&gt;

OUTPUT:

H

c_str() is primarily used when you need the string in a char array format. Many functions don't accept string data type as a valid argument. Like printf. It only accepts char.

ex: printf("%s",string.c_str());

If you want to access single characters you shouldn't need to use c_str(). You can use [][]

Let's see your source and I can try and figure out what you are doing. I'm confused why you need it at all.

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171702
Share on other sites

  • 0

alright...pretty long way now :)

...another question, quite unrelated to the previous ones...

i have a string array which contains the name of the mp3 files.

SongArray[0] = u2-stuck_in_a_moment.mp3

and i have a string array which contains the name of the artists

ArtistArray[0] = U2

now what i want to do is change the SongArray string so the artist name is omitted...and all "_", "-", ".", ".mp3"....omitted, then i want the remaining string in a new string array, so kinda like:

NameArray[0] = stuck

NameArray[1] = in

NameArray[2] = a

NameArray[3] = moment

the idea is to make the array shown above...doesn't matter how it's created. the ommitting stuff was just an option that i came up with which i thought might work, but not really sure how to go about it. if there's a better way, i'm all for it. :)

Link to comment
https://www.neowin.net/forum/topic/20293-c/#findComment-171993
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Amazon Deal: JBL BAR 1000 7.1.4, BAR 700 5.1 Dolby Atmos wireless subwoofer soundbars by Sayan Sen If you are in the market for an audio system and are after smaller bookshelf speakers delivering highly accurate sound, then take a look at KEF and Polk Audio's Q Concerto Meta and Reserve R200 speakers, respectively, as both of them are up for sale at their lowest ever prices. However, if you are more into shaking your house, which is not possible without a subwoofer, then Samsung has its Q900F, Q800F, and Q600F soundbar systems with wireless subwoofers at the lowest prices. These are the latest 2025 models, and you can take a look at them in this article here. JBL BAR 1000 For those looking for additional options, JBL's BAR 1000 and Bar 700 are also available. The former has hit its lowest ever price too, while the latter is back to its cheapest (purchase links down below). JBL claims that its BAR 1000 model goes as low as 33Hz which is crucial for movie-watching or even some genres of music. The 10-inch subwoofer is rated at 300 watts of RMS power. The total power output of the system is 880 watts at THD (total harmonic distortion) of 1%. JBL BAR 1000 rear view Unlike the 7.1.4 JBL BAR 1000, the BAR 700 is a 5.1 system which means it lacks true Dolby Atmos, but it should still provide an Atmos-like experience. DTS:X is also not supported. The BAR 700 is rated at 620 watts. It is good to see some power ratings, as companies like Samsung, Sonos, Bose, and more tend not to mention them all too often nowadays. Interestingly, both the BAR systems have similarly-specced subwoofers so if bass is what you are looking for and do not care about the Atmos experience so much, you can opt for the BAR 700 too. Get them at the links below: JBL Bar 1000: 7.1.4-Channel soundbar with Detachable Surround Speakers, MultiBeam™, True Dolby Atmos®, and DTS:X®, Black: $799.95 (Shipped and Sold by Amazon US) JBL Bar 700: 5.1-Channel soundbar with Detachable Surround Speakers and Dolby Atmos®, Black: $549.95 (Amazon US) + you also get free 90-day Amazon Music This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • Funny how just a few days ago we hear a lot of rumors that this device was cancelled.
    • Many order mixed mango yogurt.  
    • It's about the same actually. The oldest iPhone to support iOS 26 will likely be the iPhone 12, which was released in late 2020, so very similar. The current OS runs on the iPhone 11, 2019. Still, valid point, you expect to be able to use a computer for longer than a phone.
  • Recent Achievements

    • Dedicated
      Epaminombas earned a badge
      Dedicated
    • Veteran
      Yonah went up a rank
      Veteran
    • First Post
      viraltui earned a badge
      First Post
    • Reacting Well
      viraltui earned a badge
      Reacting Well
    • Week One Done
      LunaFerret earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      482
    2. 2
      +FloatingFatMan
      264
    3. 3
      snowy owl
      233
    4. 4
      ATLien_0
      231
    5. 5
      Edouard
      176
  • Tell a friend

    Love Neowin? Tell a friend!