473,686 Members | 3,587 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getline and files

KL
I am so lost. I am in a college course for C++, and first off let me
state I am not asking for anyone to do my assignment, just
clarification on what I seem to not be able to comprehend. I have a
..txt file that I want to read into a multi-dimensional string array.
Each line of the file needs to be read into the array. OK..sounds easy
enough, but I can't get the getline(file_na me array_name) to work.
So...I am thinking it is definitely operator error here on my part.
Any advice on what I am doing wrong?

KL

Jul 23 '05 #1
14 3879
KL wrote:
Any advice on what I am doing wrong?

Please post your code.
--
CrayzeeWulf
Jul 23 '05 #2
KL

CrayzeeWulf wrote:
KL wrote:
Any advice on what I am doing wrong?

Please post your code.
--
CrayzeeWulf


Yeah that probably would be helpful! Sorry!

#include<iostre am>
#include<fstrea m>
#include<cstdli b>
#include<string >
using namespace std;
int main(){
char question[50];
char string[50];
ifstream questions;
questions.open( "qs.txt");//Opens file to read questions from
getline(questio ns,string);
while(!question s.eof()){
for(int x=0; x<20; x++){
question[x]=string;
getline(questio ns,string);
}

questions.close ();
for(int ind=0; ind<20; ind++){
cout << question[ind];
}
}

And... I still can't get it to build without errors...I keep getting a
message of: c:\Documents and Settings\Kari-Lyn Bjorn\My
Documents\UA\20 05 Spring\CS114\As signments\Proje ct 7\Project
7\10435569.cpp( 33): error C2784: 'std::basic_ist ream<_Elem,_Tra its>
&std::getline(s td::basic_istre am<_Elem,_Trait s>
&,std::basic_st ring<_Elem,_Tra its,_Alloc> &)' : could not deduce
template argument for 'std::basic_ist ream<_Elem,_Tra its> &' from
'std::ifstream'

Which means nothing to me. I leave it to you experts to point out my
errors in logic, etc. (including typos, as I have done that before
too! )

KL

Jul 23 '05 #3
KL wrote:
#include<iostre am>
#include<fstrea m>
#include<cstdli b>
#include<string >
using namespace std;
int main(){
char question[50];
char string[50]; Hi KL,

It is probably not a good idea to name a variable "string" here because the
C++ STL contains a template with the same name (std::string). However, this
is a minor point and not a problem with your program.
ifstream questions;
questions.open( "qs.txt");//Opens file to read questions from
getline(questio ns,string); You are using "getline()" function here instead of using the corresponding
method of "ifstream". The function "getline()" does not take an "ifstream"
as its first argument. You should consider using something like:

questions.getli ne( string, 50 ) ;
while(!question s.eof()){
for(int x=0; x<20; x++){
question[x]=string;
In the last line above, "question[x]" has a type of "char" while the type of
"string" is "char *". You cannot assign a value of type "char *" to a
"char". What are you trying to do through the above loop ?

getline(questio ns,string);
} Once again, use ifstream::getli ne() here.


questions.close ();

This is a bad idea. You are closing the ifstream inside a "while()" loop
that might attempt to read more data from it. You should close the ifstream
once you are done with the "while()" loop.
Hope that helps.
--
CrayzeeWulf
Jul 23 '05 #4
KL

CrayzeeWulf wrote:
KL wrote:
#include<iostre am>
#include<fstrea m>
#include<cstdli b>
#include<string >
using namespace std;
int main(){
char question[50];
char string[50]; Hi KL,

It is probably not a good idea to name a variable "string" here

because the C++ STL contains a template with the same name (std::string). However, this is a minor point and not a problem with your program.
ifstream questions;
questions.open( "qs.txt");//Opens file to read questions from getline(questio ns,string); You are using "getline()" function here instead of using the

corresponding method of "ifstream". The function "getline()" does not take an "ifstream" as its first argument. You should consider using something like:

questions.getli ne( string, 50 ) ;
while(!question s.eof()){
for(int x=0; x<20; x++){
question[x]=string;
In the last line above, "question[x]" has a type of "char" while the

type of "string" is "char *". You cannot assign a value of type "char *" to a
"char". What are you trying to do through the above loop ?

getline(questio ns,string);
} Once again, use ifstream::getli ne() here.


questions.close ();

This is a bad idea. You are closing the ifstream inside a "while()"

loop that might attempt to read more data from it. You should close the ifstream once you are done with the "while()" loop.
Hope that helps.
--
CrayzeeWulf


OK so now I got:
#include<iostre am>
#include<fstrea m>
#include<cstdli b>
#include<string >
using namespace std;

int main(){
char question[50];
char qstring[50];
ifstream questions;
questions.open( "qs.txt");//Opens file to read questions from
questions.getli ne( qstring, 50 ) ;
while(!question s.eof()){
for(int x=0; x<20; x++){
question[x]=qstring;
questions.getli ne( qstring, 50 ) ;
}
}

questions.close ();

for(int ind=0; ind<20; ind++){
cout << question[ind];
}
}

I think part of my problem is that I am not understanding the array v.
string thing. I am trying to build an array of 20 strings. Each
string should be about 50 chars. Am I totally trying to do the
impossible, or am I just going about it wrong? AND I haven't even
started looking at the answers which should be a multidimensiona l array
of 20 by 6...with a total 0f 120 strings.

KL

Jul 23 '05 #5
In article <11************ **********@l41g 2000cwc.googleg roups.com>,
KL <kl*******@aol. com> wrote:
[...] I have a
.txt file that I want to read into a multi-dimensional string array.
Each line of the file needs to be read into the array.
Oh dear. Let me guess... each line of the file contains one question, and
you're supposed to set up a two-dimensional array of *characters* where
each "row" stores one question?
OK..sounds easy
enough, but I can't get the getline(file_na me array_name) to work.


Unfortunately, you've got more problems than just the getline(), if my
guess as to your task is correct. Dealing with character strings as
arrays of characters, and with collections of strings as two-dimensional
arrays of characters, is actually rather tricky and error-prone.

I'm not going to help you with doing it that way, because I wouldn't do it
that way even if someone held a gun to my head. C++ provides much better
tools for this, for six or seven years now, and instructors should not be
foisting the old methods on beginning students. Real programmers do need
to deal with this stuff in old code, but IMHO students should get a firm
grasp of the modern methods first.

Anyway, I'll content myself with presenting a modern C++ solution to your
problem, so you can compare it with the character-array solution when you
finally get it working, and hopefully you'll ask your school why your
instructor isn't staying up to date.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
//-- 'string' is the standard C++ data type for storing character
//-- strings. It is provided for you via the <string> header. It is
//-- much nicer than an array of char for storing character strings,
//-- because it automatically grows or shrinks according to how many
//-- characters it needs to accommodate, so you don't declare it with
//-- a specific size, and you don't have to worry about overflowing it.

string line; // for holding each line in turn as we read it

//-- 'vector' is a standard C++ "container" which is similar to an array,
//-- but is nicer in many ways. For example, you can add data to it in
//-- such a way that it automatically expands as necessary; unlike an
//-- array, where you have to anticipate the amount of data it will need
//-- to store, and declare it with that specific size.

//-- You can declare a vector to have a specific size initially, but here
//-- we don't know how many items we're going to put in it, so we'll let
//-- it have zero size initially and let it expand as necessary.

vector<string> questions;

ifstream questionFile;
questionFile.op en ("qs.txt");

//-- All C++ input operations, including getline(), can be used as a loop
//-- condition; if the input succeeds, getline() evaluates as 'true' in
//-- the context of the 'while' statement, and you enter or continue the
//-- loop. If the input fails, getline() evaluates as 'false' and the
//-- loop terminates.

//-- Inside the loop, we take the line that we just read from the file,
//-- and use the vector's push_back() member function to append it to the
//-- end. The vector automatically "grows" as necessary.

while (getline (questionFile, line))
{
questions.push_ back (line);
}
questionFile.cl ose();

//-- A vector's size() member function tells us how many items it contains.

for (int k = 0; k < questions.size( ); ++k)
{
cout << questions[k] << endl;
}

return 0;
}

--
Jon Bell <jt****@presby. edu> Presbyterian College
Dept. of Physics and Computer Science Clinton, South Carolina USA
Jul 23 '05 #6
KL wrote:

OK so now I got:
#include<iostre am>
#include<fstrea m>
#include<cstdli b>
#include<string >
using namespace std;

int main(){
char question[50];
char qstring[50];
ifstream questions;
questions.open( "qs.txt");//Opens file to read questions from
questions.getli ne( qstring, 50 ) ;
while(!question s.eof()){
for(int x=0; x<20; x++){
question[x]=qstring;
You are getting there. The statement above is still not right. Both
"question" and "qstring" are "arrays of characters". The expression
"question[x]" refers to a single element of the array "queston". This
element is a single character. When you use the statement
"question[x]=qstring", you are sorta trying to put an entire array into
something that can only hold a single character. The best you can do is
"question[x]=qstring[x]". I would suggest that you read more about arrays
and pointers in your text book and work through the examples and problems
to understand them better.

I think part of my problem is that I am not understanding the array v.
string thing. I am trying to build an array of 20 strings. Each
string should be about 50 chars. Am I totally trying to do the
impossible, or am I just going about it wrong? AND I haven't even
started looking at the answers which should be a multidimensiona l array
of 20 by 6...with a total 0f 120 strings.

Yes. Thinking about multidimensiona l arrays is the right direction. However,
a much better way of doing this in C++ is to use containers provided by the
C++ Standard Template Library. You should consider using std::vector and
std::string whenever you need arrays and strings.

Hope that helps.
--
CrayzeeWulf
Jul 23 '05 #7
KL

Jon Bell wrote:
In article <11************ **********@l41g 2000cwc.googleg roups.com>,
KL <kl*******@aol. com> wrote:
[...] I have a
.txt file that I want to read into a multi-dimensional string array.
Each line of the file needs to be read into the array.
Oh dear. Let me guess... each line of the file contains one

question, and you're supposed to set up a two-dimensional array of *characters* where each "row" stores one question?
OK..sounds easy
enough, but I can't get the getline(file_na me array_name) to work.
Unfortunately, you've got more problems than just the getline(), if

my guess as to your task is correct. Dealing with character strings as
arrays of characters, and with collections of strings as two-dimensional arrays of characters, is actually rather tricky and error-prone.

I'm not going to help you with doing it that way, because I wouldn't do it that way even if someone held a gun to my head. C++ provides much better tools for this, for six or seven years now, and instructors should not be foisting the old methods on beginning students. Real programmers do need to deal with this stuff in old code, but IMHO students should get a firm grasp of the modern methods first.

Anyway, I'll content myself with presenting a modern C++ solution to your problem, so you can compare it with the character-array solution when you finally get it working, and hopefully you'll ask your school why your instructor isn't staying up to date.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
//-- 'string' is the standard C++ data type for storing character
//-- strings. It is provided for you via the <string> header. It is
//-- much nicer than an array of char for storing character strings,
//-- because it automatically grows or shrinks according to how many
//-- characters it needs to accommodate, so you don't declare it with //-- a specific size, and you don't have to worry about overflowing it.
string line; // for holding each line in turn as we read it

//-- 'vector' is a standard C++ "container" which is similar to an array, //-- but is nicer in many ways. For example, you can add data to it in //-- such a way that it automatically expands as necessary; unlike an //-- array, where you have to anticipate the amount of data it will need //-- to store, and declare it with that specific size.

//-- You can declare a vector to have a specific size initially, but here //-- we don't know how many items we're going to put in it, so we'll let //-- it have zero size initially and let it expand as necessary.

vector<string> questions;

ifstream questionFile;
questionFile.op en ("qs.txt");

//-- All C++ input operations, including getline(), can be used as a loop //-- condition; if the input succeeds, getline() evaluates as 'true' in //-- the context of the 'while' statement, and you enter or continue the //-- loop. If the input fails, getline() evaluates as 'false' and the //-- loop terminates.

//-- Inside the loop, we take the line that we just read from the file, //-- and use the vector's push_back() member function to append it to the //-- end. The vector automatically "grows" as necessary.

while (getline (questionFile, line))
{
questions.push_ back (line);
}
questionFile.cl ose();

//-- A vector's size() member function tells us how many items it contains.
for (int k = 0; k < questions.size( ); ++k)
{
cout << questions[k] << endl;
}

return 0;
}

--
Jon Bell <jt****@presby. edu> Presbyterian College Dept. of Physics and Computer Science Clinton, South Carolina

USA

Thanks to you and Crazywulf...I think they are just trying to get us to
think and see arrays...I think this assignment isn't quite the way to
do it, but I am just the student. Both of your answers have been
helpful and I will try some more later this morning at school.

KL

Jul 23 '05 #8

"KL" <kl*******@aol. com> wrote in message
news:11******** *************@o 13g2000cwo.goog legroups.com...

CrayzeeWulf wrote:
KL wrote:
> Any advice on what I am doing wrong?

Please post your code.
--
CrayzeeWulf


Yeah that probably would be helpful! Sorry!

#include<iostre am>
#include<fstrea m>
#include<cstdli b>
#include<string >
using namespace std;
int main(){
char question[50];
char string[50];
ifstream questions;
questions.open( "qs.txt");//Opens file to read questions from
getline(questio ns,string);
while(!question s.eof()){
for(int x=0; x<20; x++){
question[x]=string;
getline(questio ns,string);
}


Aside from what you're discussing with CrayzeeWulf (if that *is* his real
name! :-)), you also are not using eof() correctly. I know that many
schools teach a generic read loop as "while not end of file...", but that's
not how the eof() function actually works. That function is intended to
signal why a *previous* read operation failed. Your loop needs to check the
return value of questions.getli ne(), not questions.eof() .

-Howard


Jul 23 '05 #9
KL

Jon Bell wrote:
In article <11************ **********@l41g 2000cwc.googleg roups.com>,
KL <kl*******@aol. com> wrote:
[...] I have a
.txt file that I want to read into a multi-dimensional string array.
Each line of the file needs to be read into the array.
Oh dear. Let me guess... each line of the file contains one

question, and you're supposed to set up a two-dimensional array of *characters* where each "row" stores one question?
OK..sounds easy
enough, but I can't get the getline(file_na me array_name) to work.
Unfortunately, you've got more problems than just the getline(), if

my guess as to your task is correct. Dealing with character strings as
arrays of characters, and with collections of strings as two-dimensional arrays of characters, is actually rather tricky and error-prone.

I'm not going to help you with doing it that way, because I wouldn't do it that way even if someone held a gun to my head. C++ provides much better tools for this, for six or seven years now, and instructors should not be foisting the old methods on beginning students. Real programmers do need to deal with this stuff in old code, but IMHO students should get a firm grasp of the modern methods first.

Anyway, I'll content myself with presenting a modern C++ solution to your problem, so you can compare it with the character-array solution when you finally get it working, and hopefully you'll ask your school why your instructor isn't staying up to date.
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ()
{
//-- 'string' is the standard C++ data type for storing character
//-- strings. It is provided for you via the <string> header. It is
//-- much nicer than an array of char for storing character strings,
//-- because it automatically grows or shrinks according to how many
//-- characters it needs to accommodate, so you don't declare it with //-- a specific size, and you don't have to worry about overflowing it.
string line; // for holding each line in turn as we read it

//-- 'vector' is a standard C++ "container" which is similar to an array, //-- but is nicer in many ways. For example, you can add data to it in //-- such a way that it automatically expands as necessary; unlike an //-- array, where you have to anticipate the amount of data it will need //-- to store, and declare it with that specific size.

//-- You can declare a vector to have a specific size initially, but here //-- we don't know how many items we're going to put in it, so we'll let //-- it have zero size initially and let it expand as necessary.

vector<string> questions;

ifstream questionFile;
questionFile.op en ("qs.txt");

//-- All C++ input operations, including getline(), can be used as a loop //-- condition; if the input succeeds, getline() evaluates as 'true' in //-- the context of the 'while' statement, and you enter or continue the //-- loop. If the input fails, getline() evaluates as 'false' and the //-- loop terminates.

//-- Inside the loop, we take the line that we just read from the file, //-- and use the vector's push_back() member function to append it to the //-- end. The vector automatically "grows" as necessary.

while (getline (questionFile, line))
{
questions.push_ back (line);
}
questionFile.cl ose();

//-- A vector's size() member function tells us how many items it contains.
for (int k = 0; k < questions.size( ); ++k)
{
cout << questions[k] << endl;
}

return 0;
}

--
Jon Bell <jt****@presby. edu> Presbyterian College Dept. of Physics and Computer Science Clinton, South Carolina

USA

This has been very helpful, but still in need of a bit of info. Can I
use this as a separate void function to call? And if so, what would be
the parameters? I am almost there...but getting a tad lost in the
finer points. Sigh.

KL

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
5606
by: Skywise | last post by:
I keep getting the following error upon compiling: c:\c++ files\programs\stellardebug\unitcode.h(677) : error C2664: 'class istream &__thiscall istream::getline(char *,int,char)' : cannot convert parameter 1 from 'const char *' to 'char *' Conversion loses qualifiers I have a data file called Standard.udf The Data File (not the problem): The data in the file is in text format, and was created using a function in this program with...
18
8245
by: Amadeus W. M. | last post by:
I'm trying to read a whole file as a single string, using the getline() function, as in the example below. I can't tell what I'm doing wrong. Tried g++ 3.2, 3.4 and 4.0. Thanks! #include <iostream> #include <fstream> #include <cstdlib> #include <string>
5
3641
by: allspamgoeshere3 | last post by:
Hi! I'm having trouble reading text lines from a file describing the levels for a simple game I'm creating. Inside the function that reads the content of the file there is a loop that basically looks like this ifstream file("levels\\level1.txt"); string line; getline(file, line);
7
5557
by: jccorreu | last post by:
I've got to read info from multiple files that will be given to me. I know the format and what the data is. The thing is each time we run the program we may be using a differnt number of files, with different file names each time. So i'm writing into the code to ask the user how many files, and what their names are. From each we'll read in 2 lines, then do some math using all of those lines. Then do it again on another set of lines. ...
6
6600
by: Yi Xing | last post by:
Hi, I need to read specific lines of huge text files. Each time, I know exactly which line(s) I want to read. readlines() or readline() in a loop is just too slow. Since different lines have different size, I cannot use seek(). So I am thinking of building an index for the file for fast access. Can anybody give me some tips on how to do this in Python? Thanks. Yi
0
3595
by: gasfusion | last post by:
I have a file that looks like this: string string 0 1 34 string string 0 4 5 8 3 4 the 2nd number from the left shows how many numbers are going to follow it. i.e. on the 2nd line, 4 has 5 8 3 4. Does anybody know a way to read the file? I'm trying to read it and put the data in a two dimensional array. What i have is the following function: //---------------------------------------------------------
2
5814
by: aditya.raghunath | last post by:
hi, I'm trying to read text files and then parse them. Some of these files are of several 100 Mbytes or in some cases GBytes. Reading them using the getline function slows down my program a lot, takes more than 15-20 min to read them. I want to know efficient ways to read these files. Any ideas?? TIA Aditya
6
3813
by: ankit.kumar.agarwal | last post by:
I am facing a problem with getline I am reading a text file with a getline function the lines can have '|' as separator. everything works OK but in case if i have 2 delimitors in file '234|| dfdg' so here my program does not go beyond the 2nd '|'. i am using ifstream to read the file. somehow check for eof() gets passed although end of file is not there. i am using
2
2495
by: eduardoamfm | last post by:
Hi everybody! I have the following files: (MSC.080806.00, MSC.080806.01, MSC.080806.02...) each one has the same pattern, with two different START and STOP times and values: ... START:2008/08/06 08:30:00 WED; STOP: 2008/08/06 09:00:00 WED; ... TRK KEY (COMMON_LANGUAGE_NAME) INFO (OM2TRKINFO)
0
8581
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8514
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9050
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8766
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8778
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7598
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4307
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.