从键盘读入的几种方式
#include
#include
using namespace std;
int main(){
char a[20];
cout<<"cin读取----------------"<>i>>j;
cout<>a;
cout<”
//istream &getline( char *buffer, streamsize num, char delim );
string str;
getline(cin,str);
cout<
从键盘读入数组
#include
#include
#include
using namespace std;
/*
1,5
2,3
4,5,6
2,7,9
4,9,10
*/
int main()
{
int n;
cin >> n;
vector> arrays;
for (int i = 0; i < n; i++)
{
vector input;
int number;
while (cin >> number)
{
input.push_back(number);
if (cin.get() == '\n') //按下回车键推出循环
break;
}
arrays.push_back(input);
}
cout << "\n打印:\n";
for (auto nums : arrays)
{
for (auto num : nums)
{
cout << num;
cout << ",";
}
cout << endl;
}
return 0;
}
从文件读取数据的几种方式
#include
#include
#include
using namespace std;
void ReadFile1(string filename){
//逐词读取,词之间用空格区分
ifstream f(filename);
string s;
if(f.is_open()){
while(!f.eof())
{
f>>s;
cout<<"read1:"<
从文件读取数组
#include
#include
#include
#include
#include
#include
std::vector> readMatrixFile(const char *fileName)
{
std::vector> matrixALL{};
int row = 0;
std::ifstream fileStream;
std::string tmp;
int count = 0; // 行数计数器
fileStream.open(fileName, std::ios::in); //ios::in 表示以只读的方式读取文件
if (fileStream.fail()) //文件打开失败:返回0
{
throw std::logic_error("read file fail");
}
else //文件存在
{
while (getline(fileStream, tmp, '\n')) //读取一行
{
std::cout << tmp << std::endl;
if (count == 0)
{
row = std::stoi(tmp);
}
else
{
std::vector tmpV{};
std::istringstream is(tmp);
for (int i = 0; i < row; i++)
{
std::string str_tmp;
is >> str_tmp;
tmpV.push_back(std::stod(str_tmp));
}
matrixALL.push_back(tmpV);
}
count++;
}
fileStream.close();
}
return matrixALL;
}
int main()
{
std::vector> matrixALL = readMatrixFile("../matrix.txt");
for (int i = 0; i < matrixALL.size(); i++)
{
for (int j = 0; j < matrixALL[0].size(); ++j)
{
std::cout << matrixALL[i][j];
}
std::cout << std::endl;
}
return 0;
}
写入数组到文件
#include
#include
#include
using namespace std;
int main()
{
vector nums={1,2,3};
ofstream out("输出.txt");
for(auto num:nums)
out<