注意区分readline和readlines区别
用readline:
file=open("C:/Users/24330/Desktop/eve.txt") #(C:\Users\24330\Desktop\eve.txt)
#注意windows里面的文件路径是\右斜杠 在打开文件的时候要用/左斜杠
#而且如果txt文件位置和代码位置一样的话可以直接写“eve.txt"
#要注意这里的引号不能漏掉
line=file.readline()
while line:
print line
line=file.readline()
file.close()
#要记得close这个file 虽然看起来没有close也不会影响程序运行
#如果open的文件存放的地方是临时的那么会自动关闭文件句柄
# 但是如果是个固定的变量 不close的话不会释放句柄
用readlines:
file=open("eve.txt")
lines=file.readlines()
for i in lines:
print i
file.close()
C++:
首先我们要了解c++的IO库类型和头文件 也就是input output输入输出库
头文件
头文件 | 类型 |
---|---|
iostream | istream 从流读取数据 ostream向流写数据 iostream读写流 |
fstream | ifstream 从文件读取数据 ofstream向文件写数据 fstream 读写数据 |
sstream | istringstream 从string读数据 ostringstream向string写入stringstream读写string |
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void OutPutAnEmptyLine() //用来输出一个空行
{
cout << " \n";
}
void ReadDataFromFileWBW() //一个一个单词读取 单词间空格隔开
{
ifstream fin("aim.txt");
string s;
while (fin >> s)
{
cout << s << endl;
}
}
void ReadDataFromFileLBLIntoCharArray() //一行一行读取 内容存入数组
{
ifstream fin("aim.txt"); // c++语言里面绝对路径要用\\ 向右双斜杠
const int LINE_LENGTH = 100;
char str[LINE_LENGTH];
while (fin.getline(str, LINE_LENGTH))
{
cout << str << endl;
}
}
void ReadDataFromFileLBLIntoString() //比数组好 大小不限制 更灵活的按行读取
{
ifstream fin("aim.txt");
string s;
while (getline(fin, s))
{
cout << s << endl;
}
}
void ReadDataWithErrChecking()
{
string filename = "aim.txt";
ifstream fin(filename.c_str());
if (!fin)
{
cout << "Error opening " << filename << " for input" << endl;
exit(-1);
}
}
int main()
{
ReadDataFromFileWBW(); //word by word
OutPutAnEmptyLine();
ReadDataFromFileLBLIntoCharArray(); // line by line存入数组
OutPutAnEmptyLine();
ReadDataFromFileLBLIntoString(); //line by line 放入string
OutPutAnEmptyLine();
ReadDataWithErrChecking();
system("pause");
return 0;
}
接下来是写给新手的 :
现在你有了一段代码你要是觉得你就成了 那就错了 我们看下不同环境怎么让这个代码跑起来
windows:
在visual studio里面你可能会遇到不少障碍 这里记录一个 dos窗口一闪而过的解决方法
记住你的cout 并不是在输出窗口 而是在dos窗口
方法一:
在“解决方案”窗口中,右击项目名称,点击“属性” --> “配置属性” --> "链接器“ --> ”系统“ --> "子系统” , 在下拉菜单中选择“控制台(/SUBSYSTEM:CONSOLE )
方法二:
如果你写了return 0
在前面加上 system(“pause”);
因为程序运行完了 dos窗口就会关掉 想要窗口保持着就要写个让程序暂停的命令
方法三:
打开power shell 把.exe文件拖进去运行
ubuntu
以c++为例
先看下自己有没有g++
在终端里输入 g++ --version
有的话
输入 g++ test.cpp
他会自动生成一个a.out在你代码的同文件下
终端输入 ./a.out 就可以查看里面的内容了
如果想换个名字就 终端输入 g++ -o myname test.cpp
如果还想终端直接查看编译过的内容 那就输入
g++ -o myname&./myname test.cpp
其实还是要先编译 只是两个指令并在一起打而已
说的很全了 喜欢的老铁 留个赞?