关于getline函数的问题 [英] question about getline function

查看:95
本文介绍了关于getline函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream.h>
#include <conio.h>
#include <fstream.h>
void main()
{
clrscr();
ifstream g;
char str[100];
g.open("a.txt");
while(str!='\n') problem is here
{
g.getline(str,20);
cout<<str;
}
g.close();
getch();
}





我读到getline函数读取了一个字符序列,直到达到行尾('\ n'' )

但我的程序无法正常工作



I read that getline functions reads a seqpence of character untill end of line is reached('\n')
but my program can not work

推荐答案

Quote:

我的程序无法正常工作



不,它不能。

从来没有一个点 str 指向100 char s的指针将等于常数值'\ n'如果我没记错的话会被评估为 13

你的,而循环永远不会完成。如果你只想阅读一行但我不确定你要做什你检查你对指针的理解。很多人在C / C ++中发现这个难题。


No it cannot.
There is never going to be a point where str a pointer to 100 chars is going to be equal to the constant value '\n' which if I remember correctly is evaluated as 13.
Your while loop will never complete. Your while loop is also possibly unnecessary if you only want to read one line but I don't know for sure what you're trying to do.

I would recommend you check your understanding of pointers. Many people find this a difficult topic in C/C++.


我已经为你修改了你的程序,这里是代码:



I have modified your program for you, here is the code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{

	ifstream g;

	char str[100];

	g.open("a.txt");

        /* repeat following actions 
           until end of file is reached */

	while( ! g.eof() ) 
	{
                /* clear our string, so we can get
                   new data */

		memset( &str, '\0', sizeof(str) );
		
                // get 100 characters into str
	
		g.getline(str,100);

                // write the result, and go to new line

		cout<<str<<endl;
		
	}

	g.close();

	return 0;
}





我已经处理了这个问题已经有一段时间了,但我希望这会对你有帮助。

祝您好运!



It has been a while since I have dealt with this, but I hope that this will help you.
Best regards and good luck!


这篇关于关于getline函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆