将文件每一行读入到string类型的vector 对应一个元素中

这篇博客探讨了在C++中如何将文件的每一行读取并存储到一个string类型的vector中。在尝试解决C++ Primer中的第8.9题时,作者遇到了4个编译警告,主要涉及std::reverse_iterator和std::vector的使用。警告发生在D:Program FilesMicrosoft Visual StudioMyProjects标准IO库2标准IO库2.CPP的31行以及包含的头文件中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

C++Primer 习题8.9, P102

书 P254

#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
void main()
{
	string s,filename = "c:/ludashi.txt";
	vector<string> svect;	
	ifstream infile(filename.c_str());
	if(!infile ){
		cerr << "Error opening file";  
		  exit(EXIT_FAILURE);  
	}	
	while(getline(infile,s)){
		   svect.push_back(s);
	}
	infile.close();
	infile.clear();		

	for(vector<string>::iterator it=svect.begin();it!=svect.end();++it)
		cout<<*it<<endl;

}

 

 

出现4个警告warnings ,搞不清楚怎么回事.


D:\Program Files\Microsoft Visual Studio\MyProjects\标准IO库2\标准IO库2.CPP(31) : warning C4786: 'std::reverse_iterator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > const *,std::basic_string<char,std::char_traits<char>,std::

### 如何正确读取包含空格的二维 `string` 数组 在 C++ 中,如果要处理包含空格的字符串输入,通常可以借助标准库中的 `std::getline()` 函数来实现。对于二维字符串数组的情况,可以通过嵌套循环逐行读取数据,并将其存储到对应的二维容器中。 以下是具体方法以及代码示例: #### 使用 `vector<vector<string>>` 存储二维字符串数组 为了更灵活地管理动态大小的数据结构,推荐使用 STL 容器 `std::vector<std::vector<std::string>>` 来代替传统的固定大小数组[^1]。 ```cpp #include <iostream> #include <vector> #include <string> int main() { int rows, cols; std::cout << "Enter the number of rows and columns: "; std::cin >> rows >> cols; // 清除缓冲区中的多余字符(如换行符) std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::vector<std::vector<std::string>> matrix(rows, std::vector<std::string>(cols)); std::cout << "Enter the elements (with spaces):" << std::endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::getline(std::cin, matrix[i][j]); } } std::cout << "\nThe entered data is:" << std::endl; for (const auto& row : matrix) { for (const auto& str : row) { std::cout << "\"" << str << "\"\t"; } std::cout << std::endl; } return 0; } ``` #### 关键点解析 1. **清除输入流缓冲区** 在从控制台接收整数后,需要调用 `std::cin.ignore(...)` 将可能残留的换行符或其他空白字符移除,以免影响后续基于 `std::getline()` 的输入操作[^4]。 2. **逐行列举输入** 利用双重循环遍历每一行和列的位置,通过 `std::getline(std::cin, ...)` 获取完整的字符串内容,即使其中含有空格也能被保留下来[^3]。 3. **输出验证** 输出时加双引号包裹每个字符串以便清晰展示其边界,尤其是当某些单元格为空白串的情况下更容易区分。 --- #### 注意事项 - 如果矩阵规模较大或者不确定最终尺寸,则应考虑采用动态分配方式创建内存区域。 - 对于多维数组初始化问题,在实际应用过程中需注意避免越界访问错误。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值