[英]User-input file path
The program is supposed to open a text file whose path is user-input. 该程序应该打开一个文本文件,其路径是用户输入的。 Next, it counts the lines contained in the file and outputs them.
接下来,它计算文件中包含的行并输出。 Here's what I tried:
这是我尝试过的:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string path = NULL;
string garbage = NULL;
int cnt = 0;
cout << "Enter file path: ";
cin >> path;
ifstream inFile(path.c_str());
if (inFile)
{
while (!inFile.eof())
{
getline(inFile, garbage);
++cnt;
}
}
inFile.close();
cout << endl;
cout << path << " has " << cnt << " lines";
cin.ignore();
cin.get();
return 0;
}
This is what I get: 这是我得到的:
Program: C:\\Windows\\SYSTEM32\\MSVCP120D.dll File: c:\\program files (x86)\\microsoft visual studio 12.0\\vc\\include\\xstring Line: 1168 Expression: invalid null pointer 程序:C:\\ Windows \\ SYSTEM32 \\ MSVCP120D.dll文件:c:\\ program files(x86)\\ microsoft visual studio 12.0 \\ vc \\ include \\ xstring行:1168表达式:无效的空指针
Note: The course I'm following has only shown me the basics of the methods used by ifstream and ofstream, like open, close and eof. 注意:我所遵循的课程仅向我展示了ifstream和ofstream使用的方法的基础,例如open,close和eof。 So I would appreciate a solution with only these, as I'm sure you know many ways of doing this.
因此,仅凭这些,我将不胜感激,因为我敢肯定您知道这样做的许多方法。
The class std::string
is a reasonable container class, like std::vector
but with an API that has a number of extra string-oriented functions. 类
std::string
是一个合理的容器类,类似于std::vector
但具有一个具有许多额外的面向字符串的函数的API。
In a particular, its use does not resemble old-fashioned C-style string handling in terms of char*
, which is where I assume you got the idea of trying to use NULL
as an initializer. 在一个特定的,在使用时不会像老式的C风格的字符串中的条款处理
char*
,这是我认为你有试图利用这个想法NULL
作为初始化。 (in modern C++ you should use the C++ keyword nullptr
to create a null pointer, rather than the old C style macro NULL
) (在现代C ++中,应使用C ++关键字
nullptr
创建空指针,而不是使用旧的C样式宏NULL
)
what string path = NULL;
什么
string path = NULL;
actually does is interpret NULL
as a const char*
, and then tries to read the C-style string at the location NULL
points to so as to copy it into path
. 实际上所做的是将
NULL
解释为const char*
,然后尝试在NULL
指向的位置读取C样式的字符串,以便将其复制到path
。 Since NULL
is null rather than actually pointing to a string, you get the error message you cite. 由于
NULL
为null而不是实际指向字符串,因此您会收到引用的错误消息。
What you really want to do is to simply use the default constructor via string path;
您真正想要做的就是通过
string path;
简单地使用默认构造函数string path;
which initializes path
to be an empty string. 将
path
初始化为空字符串。
Don't use the meaningless NULL
they're not pointers: 不要使用无意义的
NULL
而不是指针:
string path;
string garbage;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.