在C ++中,我正在处理一个代码,该文件在.txt文件中创建用于组织货币的表格,并且我遇到一个问题,如果您输入的行数不完全是10,则分隔列的行将不匹配数字/字母放入框中。有关如何解决此问题的任何想法?
这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ofstream outputFile;
double monday, tuesday, wednesday, thursday, friday;
int columns;
string categories;
outputFile.open("organize.txt");
cout << "How many columns do you need in your table? ";
cin >> columns;
outputFile << "| Categories | Monday | Tuesday | Wednesday | Thursday | Friday |\n";
outputFile << "|------------|------------|-----------|-------------|------------|------------|\n";
for (int count = 1; count <= columns; count++)
{
cout << "Enter category (no more than "
<< count << ": ";
cin >> categories;
outputFile <<"| " << categories;
}
outputFile.close();
return 0;
}
基本上,我需要能够阻止用户输入超过10个字母/数字,同时如果用户使用的字符少于10个,则要提供空白空间来填充该区域。
答案 0 :(得分:1)
尽管尚不清楚您打算如何填充Monday - Friday
列,但以"Categories"
列为第一列,您可以使用std::setw()
来确保正确填充该列。查看"Categories"
列,该列最多包含10个字符,两个空格(每侧一个)和2- | (每边一个),您拥有14个字符的总宽度。
由于categories
为std::string
,因此在从用户那里输入输入后,您会发现用categories.size()
输入的字符数。因此,要从用户那里读取类别,请输出类别(在"| "
之后),然后计算可用于填充字段其余部分(为最后'|'
留出空间)所需的字符数:
std::setw(14-categories.size()-1)
将您的示例放在一起,用您可以执行的用户输入填充第一Categories
列:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
int main (void) {
std::ofstream outputFile;
// double monday, tuesday, wednesday, thursday, friday;
int columns = 0;
std::string categories;
outputFile.open("organize.txt");
std::cout << "How many columns do you need in your table? ";
if (!(std::cin >> columns)) {
std::cerr << "stream error on input.\n";
return 1;
}
outputFile << "| Categories | Monday | Tuesday | Wednesday "
"| Thursday | Friday |\n";
outputFile << "|------------|------------|-----------|-------------"
"|------------|------------|\n";
for (int count = 0; count < columns; count++)
{
std::cout << "Enter category (" << count+1 << "/" << columns << "): ";
std::cin >> categories;
outputFile << "| " << categories << std::setw(14-categories.size()-1)
<< "|\n";
}
outputFile.close();
return 0;
}
使用/输出示例
$ ./bin/cout_columns
How many columns do you need in your table? 7
Enter category (1/7): nuts
Enter category (2/7): bolts
Enter category (3/7): screws
Enter category (4/7): nails
Enter category (5/7): staples
Enter category (6/7): pliars
Enter category (7/7): hammer
输出文件
$ cat organize.txt
| Categories | Monday | Tuesday | Wednesday | Thursday | Friday |
|------------|------------|-----------|-------------|------------|------------|
| nuts |
| bolts |
| screws |
| nails |
| staples |
| pliars |
| hammer |
那种简而言之就是您将剩下的列按大小排列并填充每个列的方式。面临的挑战是,在开始写入文件之前,您将必须为每个类别提供整周的数据,因为无法备份并在以后填写它们。
仔细检查一下,让我知道这是您要的还是有任何疑问。